首先推荐官方文档
https://www.npmjs.com/package/mysql
连接mysql数据库
从node库中引用mysql后,可以用createConnection()创建一个连接,需要将一些配置参数传给函数
var mysql = require('mysql');
var connection = mysql.createConnection({
host : 'localhost',
user : 'me',
password : 'secret',
database : 'my_db'
});
数据库连接的建立与关闭
通过mysql.createConnection()后可以获得一个mysql connection对象,可以通过这个对象调用connect()或者end()来建立或关闭连接。
connection.connect(); // 连接建立
connection.end(); // 连接关闭
注意:由于在node中的网路请求是异步的,所以数据库查询操作也是异步的,通过一个任务队列来依次执行,所以end()
并不会直接关闭,而是将存在任务队列中的任务都发送出去后再关闭。
以下是官网原文
- Every method you invoke on a connection is queued and executed in sequence.
- Closing the connection is done using
end()
which makes sure all remaining queries are executed before sending a quit packet to the mysql server.
数据库连接不关闭运行运行程序后程序是不会停止的,要手动Ctrl+C才会停止
这是一个官网建议的连接实例
var mysql = require('mysql');
var connection = mysql.createConnection({
host : 'example.org',
user : 'bob',
password : 'secret'
});
connection.connect(function(err) {
if (err) {
console.error('error connecting: ' + err.stack);
return;
}
console.log('connected as id ' + connection.threadId);
});
简单的增删改查CURD
我现在有一个表,表中只有两个列
- id 自增主键
- name varchar类型
执行sql语句的方法
- 直接将要执行的sql语句放入
connection.query(`delete from test where id= 1`, (error, results) => {
if (error) throw error;
console.log(results);
});
2.用?替换sql执行时需要更改的参数
将需要作为参数的部分用?代替,在后面传入参数作为?依次顺序对应的值,需要注意的是,?替换进去的字符串值会被默认加上' ',比如这个"测试问号"和2被替换进?后sql语句是这样的update test set name = '测试问号' where id = 2
connection.query(`update test set name = ? where id = ?`, ["测试问号", 2], (error, results) => {
if (error) throw error;
console.log(results);
});
3.设置执行参数
sql执行时可以带超时参数,替换?值参数
connection.query({
sql: `update test set name = ? where id = ?`,
timeout: 40000, // 40s
values: ["测试问号", 2]
}, function (error, results, fields) {
if (error) throw error;
console.log(results);
});
接着引用官方的连接实例来一个完整的增删查改:
var mysql = require('mysql');
var connection = mysql.createConnection({
host : 'example.org',
user : 'bob',
password : 'secret'
});
connection.connect(function(err) {
if (err) {
console.error('error connecting: ' + err.stack);
return;
}
console.log('connected as id ' + connection.threadId);
});
// 增
connection.query(`insert into test(name) values(?)`,"测试",(error, results) =>{
if (error) throw error;
console.log(results);
});
// 删
connection.query(`delete from test where id= ?`,1,(error, results) =>{
if (error) throw error;
console.log(results);
});
// 查
connection.query('SELECT * from test', function (error, results, fields) {
if (error) throw error;
console.log("查询结果是");
console.log(results);
});
// 改
connection.query(`update test set name = "测试修改" where id = 2`,(error, results) =>{
if (error) throw error;
console.log(results);
});
// 关闭连接
connection.end();
运行结果:
connected as id 286718
OkPacket {
fieldCount: 0,
affectedRows: 1,
insertId: 5,
serverStatus: 2,
warningCount: 0,
message: '',
protocol41: true,
changedRows: 0 }
OkPacket {
fieldCount: 0,
affectedRows: 1,
insertId: 0,
serverStatus: 2,
warningCount: 0,
message: '',
protocol41: true,
changedRows: 0 }
查询结果是
[ RowDataPacket { id: 2, name: 'change Hellow JabinGP again' },
RowDataPacket { id: 3, name: '测试' },
RowDataPacket { id: 4, name: '测试' },
RowDataPacket { id: 5, name: '测试' } ]
OkPacket {
fieldCount: 0,
affectedRows: 1,
insertId: 0,
serverStatus: 2,
warningCount: 0,
message: '(Rows matched: 1 Changed: 1 Warnings: 0',
protocol41: true,
changedRows: 1 }