search
HomeWeb Front-endJS TutorialNode.js method example for connecting to MySQL

Node.js method example for connecting to MySQL

Mar 02, 2018 am 11:30 AM
javascriptmysqlnode.js

In this article, we mainly introduce how to use Node.js to connect to MySQL and operate the database. The Websites table SQL file used in this tutorial: websites.sql, I hope it can be helpful to everyone.

Installing the driver

This tutorial uses Taobao’s customized cnpm command for installation:

$ cnpm install mysql

Connect to the database

Modify in the following examples according to your actual situation Configure and modify the database user name, password and database name:

test.js file code:

var mysql      = require('mysql');
var connection = mysql.createConnection
({  host     : 'localhost',  user     :
 'root',  password : '123456',  database : 'test'});
  connection.connect(); connection.query
  ('SELECT 1 + 1 AS solution', function 
  (error, results, fields) {  if (error)
   throw error;  console.log
   ('The solution is: ', results[0]
   .solution);}
   );

Execute the following command and the output will be:

$ node test.js
The solution is: 2

数据库连接参数说明:

参数 描述
host 主机地址 (默认:localhost)
user 用户名
password 密码
port 端口号 (默认:3306)
database 数据库名
charset 连接字符集(默认:'UTF8_GENERAL_CI',注意字符集的字母都要大写)
localAddress 此IP用于TCP连接(可选)
socketPath 连接到unix域路径,当使用 host 和 port 时会被忽略
timezone 时区(默认:'local')
connectTimeout Connection timeout (default: no limit; unit: milliseconds)
stringifyObjects Whether to serialize objects
typeCast Whether to convert column values ​​into local JavaScript type values ​​(default: true)
queryFormat Custom query statement formatting method
supportBigNumbers When the database supports bigint or decimal type columns, you need to set this option to true (default: false)
bigNumberStrings supportBigNumbers and bigNumberStrings enable forcing bigint or decimal columns to be returned as JavaScript string types (default: false)
dateStrings Force timestamp, datetime, and data types to be returned as string types instead of JavaScript Date types (default: false)
debug Enable debugging ( Default: false)
multipleStatements Whether to allow multiple MySQL statements in one query (default: false)
flags is used to modify the connection flags
ssl Use the ssl parameter (the same format as the crypto.createCredenitals parameter) or a ssl configuration file name containing The string, currently only bundles the Amazon RDS configuration file

更多说明可参见:https://github.com/mysqljs/mysql


数据库操作( CURD )

在进行数据库操作前,你需要将本站提供的 Websites 表 SQL 文件websites.sql 导入到你的 MySQL 数据库中。

本教程测试的 MySQL 用户名为 root,密码为 123456,数据库为 test,你需要根据自己配置情况修改。

查询数据

将上面我们提供的 SQL 文件导入数据库后,执行以下代码即可查询出数据:

查询数据

var mysql  = require('mysql');   
var connection = mysql.createConnection
({       host     : 'localhost',       
  user     : 'root',               
   password : '123456',         
   port: '3306',                     
   database: 'test', });  
   connection.connect(); 
   var  sql = 'SELECT * FROM websites';
   //查connection.query(sql,function (err, result) 
   {        if(err)
   {          console.log('[SELECT ERROR] - ',err.message);          return;        }
           console.log('--------------------------SELECT----------------------------');       
           console.log(result);       
           console.log('------------------------------------------------------------\n\n');  }); 
           connection.end();

执行以下命令输出就结果为:

$ node test.js--------------------------SELECT----------------------------[ RowDataPacket {
    id: 1,
    name: 'Google',
    url: 'https://www.google.cm/',
    alexa: 1,
    country: 'USA' },
  RowDataPacket {
    id: 2,
    name: '淘宝',
    url: 'https://www.taobao.com/',
    alexa: 13,
    country: 'CN' },
  RowDataPacket {
    id: 3,
    name: '菜鸟教程',
    url: 'http://www.runoob.com/',
    alexa: 4689,
    country: 'CN' },
  RowDataPacket {
    id: 4,
    name: '微博',
    url: 'http://weibo.com/',
    alexa: 20,
    country: 'CN' },
  RowDataPacket {
    id: 5,
    name: 'Facebook',
    url: 'https://www.facebook.com/',
    alexa: 3,
    country: 'USA' } ]------------------------------------------------------------

插入数据

我们可以向数据表 websties 插入数据:

插入数据

var mysql  = require('mysql');   
var connection = mysql.createConnection
({       host     : 'localhost',         
user     : 'root',               
password : '123456',         port: '3306',                     database: 'test', });  
connection.connect(); var  addSql = 'INSERT INTO websites(Id,name,url,alexa,country) 
VALUES(0,?,?,?,?)';var  addSqlParams = ['菜鸟工具', 'https://c.runoob.com','23453', 'CN'];
//增connection.query(addSql,addSqlParams,function (err, result) {        if(err)
{         console.log('[INSERT ERROR] - ',err.message);         return;        }                
console.log('--------------------------INSERT----------------------------');       
//console.log('INSERT ID:',result.insertId);               console.log('INSERT ID:',result);               
console.log('-----------------------------------------------------------------\n\n');  }); 
connection.end();

执行以下命令输出就结果为:

$ node test.js--------------------------INSERT----------------------------INSERT ID: OkPacket {
  fieldCount: 0,
  affectedRows: 1,
  insertId: 6,
  serverStatus: 2,
  warningCount: 0,
  message: '',
  protocol41: true,
  changedRows: 0 }-----------------------------------------------------------------

执行成功后,查看数据表,即可以看到添加的数据:

更新数据

我们也可以对数据库的数据进行修改:

更新数据

var mysql  = require('mysql');   var connection = mysql.createConnection({       host     : 'localhost',         user     : 'root',                password : '123456',         port: '3306',                     database: 'test', });  connection.connect(); var modSql = 'UPDATE websites SET name = ?,url = ? WHERE Id = ?';var modSqlParams = ['菜鸟移动站', 'https://m.runoob.com',6];//改connection.query(modSql,modSqlParams,function (err, result) {   if(err){         console.log('[UPDATE ERROR] - ',err.message);         return;   }          console.log('--------------------------UPDATE----------------------------');  console.log('UPDATE affectedRows',result.affectedRows);  console.log('-----------------------------------------------------------------\n\n');}); connection.end();

执行以下命令输出就结果为:

--------------------------UPDATE----------------------------UPDATE affectedRows 1-----------------------------------------------------------------

执行成功后,查看数据表,即可以看到更新的数据:

删除数据

我们可以使用以下代码来删除 id 为 6 的数据:

删除数据

var mysql  = require('mysql');   
var connection = mysql.createConnection
({       host     : 'localhost',         
user     : 'root',                password : '123456',         
port: '3306',                     database: 'test', });  
connection.connect(); var delSql = 'DELETE FROM websites where id=6';
//删connection.query(delSql,function (err, result) {        if(err)
{          console.log('[DELETE ERROR] - ',err.message);          
return;        }                
console.log('--------------------------DELETE----------------------------');       
console.log('DELETE affectedRows',result.affectedRows);       
console.log('-----------------------------------------------------------------\n\n');  }); 
connection.end();

执行以下命令输出就结果为:

--------------------------DELETE----------------------------DELETE affectedRows 1-----------------------------------------------------------------

执行成功后,查看数据表,即可以看到 id=6 的数据已被删除:

相关推荐:

PHP 使用 ODBC 连接 Mysql 数据库_PHP教程

php 连接 mysql数据库操作类_PHP教程

node.js 开发指南 – Node.js 连接 MySQL 并进行数据库操作_node.js

The above is the detailed content of Node.js method example for connecting to MySQL. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Python vs. JavaScript: Community, Libraries, and ResourcesPython vs. JavaScript: Community, Libraries, and ResourcesApr 15, 2025 am 12:16 AM

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

From C/C   to JavaScript: How It All WorksFrom C/C to JavaScript: How It All WorksApr 14, 2025 am 12:05 AM

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

JavaScript Engines: Comparing ImplementationsJavaScript Engines: Comparing ImplementationsApr 13, 2025 am 12:05 AM

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

Beyond the Browser: JavaScript in the Real WorldBeyond the Browser: JavaScript in the Real WorldApr 12, 2025 am 12:06 AM

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.

Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Apr 11, 2025 am 08:23 AM

I built a functional multi-tenant SaaS application (an EdTech app) with your everyday tech tool and you can do the same. First, what’s a multi-tenant SaaS application? Multi-tenant SaaS applications let you serve multiple customers from a sing

How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration)How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration)Apr 11, 2025 am 08:22 AM

This article demonstrates frontend integration with a backend secured by Permit, building a functional EdTech SaaS application using Next.js. The frontend fetches user permissions to control UI visibility and ensures API requests adhere to role-base

JavaScript: Exploring the Versatility of a Web LanguageJavaScript: Exploring the Versatility of a Web LanguageApr 11, 2025 am 12:01 AM

JavaScript is the core language of modern web development and is widely used for its diversity and flexibility. 1) Front-end development: build dynamic web pages and single-page applications through DOM operations and modern frameworks (such as React, Vue.js, Angular). 2) Server-side development: Node.js uses a non-blocking I/O model to handle high concurrency and real-time applications. 3) Mobile and desktop application development: cross-platform development is realized through ReactNative and Electron to improve development efficiency.

The Evolution of JavaScript: Current Trends and Future ProspectsThe Evolution of JavaScript: Current Trends and Future ProspectsApr 10, 2025 am 09:33 AM

The latest trends in JavaScript include the rise of TypeScript, the popularity of modern frameworks and libraries, and the application of WebAssembly. Future prospects cover more powerful type systems, the development of server-side JavaScript, the expansion of artificial intelligence and machine learning, and the potential of IoT and edge computing.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

Atom editor mac version download

Atom editor mac version download

The most popular open source editor