Node.js Connect to MySQL
In this chapter we will introduce how to use Node.js to connect to MySQL and perform operations on the database.
If you do not yet have basic knowledge of MySQL, you can refer to our tutorial:MySQL Tutorial。
The SQL file for the Websites table used in this tutorial:websites.sql。
Install the Driver
This tutorial usesthe Taobao customized cnpm commandto install:
$ cnpm install mysql
Connect to the database
In the following examples, modify the database username, password, and database name according to your actual configuration:
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
)
;
}
)
;
Executing the following command produces this result:
$ node test.js
The solution is: 2
Database connection parameter description:
| Parameters | Description |
|---|---|
| host | Host address (default: localhost) |
| user | Username |
| password | Password |
| port | Port number (default: 3306) |
| database | Database name |
| charset | Connection character set (default: 'UTF8_GENERAL_CI'; note that all letters of the character set must be uppercase) |
| localAddress | This IP is used for TCP connections (optional) |
| socketPath | Connect to a unix domain path; ignored when host and port are used |
| timezone | Time zone (default: 'local') |
| connectTimeout | Connection timeout (default: unlimited; unit: milliseconds) |
| stringifyObjects | Whether to serialize objects |
| typeCast | Whether to convert column values to native JavaScript type values (default: true) |
| queryFormat | Custom query statement formatting method |
| supportBigNumbers | When the database supports bigint or decimal type columns, this option needs to be set to true (default: false) |
| bigNumberStrings | Enabling supportBigNumbers and bigNumberStrings forces bigint or decimal columns to be returned as JavaScript strings (default: false) |
| dateStrings | Force timestamp, datetime, and data types to be returned as strings instead of JavaScript Date objects (default: false) |
| debug | Enable debugging (default: false) |
| multipleStatements | Whether to allow multiple MySQL statements in one query (default: false) |
| flags | Used to modify connection flags |
| ssl | Use the ssl parameter (in the same format as the crypto.createCredenitals parameter) or a string containing the name of an ssl configuration file; currently only the Amazon RDS configuration file is bundled |
For more details, see:https://github.com/mysqljs/mysql
Database Operations ( CURD )
Before performing database operations, you need to import the SQL file for the Websites table provided by this sitewebsites.sql into your MySQL database.
This tutorial tests with a MySQL username of root, a password of 123456, and a database of test; you need to modify these according to your own configuration.
Query data
After importing the SQL file provided above into the database, execute the following code to query the data:
Query data
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
'
;
//
Read
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
(
)
;
Executing the following command produces this result:
$ 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: 'Runoob Tutorial',
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' } ]
------------------------------------------------------------
Insert data
We can insert data into the websties table:
Insert data
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
=
[
'
Runoob Tools
'
,
'
https://c.runoob.com
'
,
'
23453
'
,
'
CN
'
]
;
//
Create
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
(
)
;
Executing the following command produces this result:
$ node test.js
--------------------------INSERT----------------------------
INSERT ID: OkPacket {
fieldCount: 0,
affectedRows: 1,
insertId: 6,
serverStatus: 2,
warningCount: 0,
message: '',
protocol41: true,
changedRows: 0 }
-----------------------------------------------------------------
After successful execution, view the data table to see the added data:

Update data
We can also modify the data in the database:
Update data
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
=
[
'
Runoob Mobile Site
'
,
'
https://m.runoob.com
'
,
6
]
;
//
Update
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
(
)
;
Executing the following command produces this result:
--------------------------UPDATE----------------------------
UPDATE affectedRows 1
-----------------------------------------------------------------
After successful execution, view the data table to see the updated data:

Delete data
We can use the following code to delete the data with id 6:
Delete data
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
'
;
//
Delete
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
(
)
;
Executing the following command produces this result:
--------------------------DELETE----------------------------
DELETE affectedRows 1
-----------------------------------------------------------------
After successful execution, view the data table to see that the data with id=6 has been deleted:
