Node.js笔记-node.js连接MySQL与增删改查
Posted IT1995
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Node.js笔记-node.js连接MySQL与增删改查相关的知识,希望对你有一定的参考价值。
最近在看一个开源项目,项目用的是node.js,在此学习下他的连接mysql与增删改查。
安卓mysql包:
npm install mysql
程序运行截图如下:
D:\\node\\content\\node.exe MySqlDemo
insert success
insert success
[
RowDataPacket { id: 1, name: '小明' },
RowDataPacket { id: 2, name: '小钢' }
]
update success
[
RowDataPacket { id: 1, name: '小明' },
RowDataPacket { id: 2, name: '小刚' }
]
delete success
[ RowDataPacket { id: 2, name: '小刚' } ]
delete success
源码如下:
let mysql = require('mysql');
let connection = mysql.createConnection({
host : '122.xxx.xxx.xxx',
user : 'root',
password: 'xxxxxxxxxxxx',
database : 'nodeDemo'
});
connection.connect();
function queryRecords(){
let selectSql = 'select * from my_test';
connection.query(selectSql, function (err, results, fields) {
if(err){
console.log("select error:", err.message);
return;
}
console.log(results);
})
}
function updateRecord(id, name) {
let updateSql = 'update my_test set name = ? where id = ?';
let para = [name, id];
connection.query(updateSql, para, function (err, result) {
if(err){
console.log("update error:", err.message);
return;
}
console.log("update success");
})
}
function deleteRecord(id) {
let deleteSql = 'delete from my_test where id = ?';
connection.query(deleteSql, id, function (err, result) {
if(err){
console.log("delete error:", err.message);
return;
}
console.log("delete success");
})
}
function insertRecord(id, name) {
let insertSql = 'insert into my_test(id, name) value(?, ?)';
let para = [id, name];
connection.query(insertSql, para, function (err, result) {
if(err){
console.log("insert error:", err.message);
return;
}
console.log("insert success");
})
}
function run() {
insertRecord(1, '小明');
insertRecord(2, '小钢');
queryRecords();
updateRecord(2, '小刚');
queryRecords();
deleteRecord(1);
queryRecords();
deleteRecord(2);
}
run()
以上是关于Node.js笔记-node.js连接MySQL与增删改查的主要内容,如果未能解决你的问题,请参考以下文章
Nodejs学习笔记--- 与MySQL交互(felixge/node-mysql)
node.js 服务器是不是应该与 mysql 实例建立单一连接?