node中实现与数据库的交互,实现增删改查操作
// 先npm init 初始化 然后下载 npm i mysql -S let mysql = require("mysql") // 创建链接 var connection = mysql.createConnection({ host: 'localhost', user: 'root', password: '12345678',//数据库密码 database: "4399"//数据库名称 }); // 打开链接 connection.connect();
增加操作
var addSql = `INSERT INTO message(id,name,comment) VALUES (?,?,?)`; var addSqlParams = [query.id,query.name, query.comment] connection.query(addSql,addSqlParams, function (error, results, fields) { if (error) { console.log("失败"); } else { console.log('The solution is: ', results); } });
//关闭链接 connection.end();
修改操作
var upSql = `update message set name = ?,comment = ? where id = ?`; var upSqlParams = [query.name, query.comment, idnum] //idnum为其他内容中赋予的值,当作id使用 connection.query(upSql, upSqlParams, function (error, results, fields) { if (error) { console.log("失败"); } else { console.log('The solution is: ', results); console.log(query.id); console.log(query.name); console.log(query.comment); } });
查询
connection.query('select * from message order by id desc', function (error, results, fields) { if (error) { console.log(error); } else { // console.log('The solution is: ', results); response.end(template.render(data.toString(), { messageList:results})) } }) connection.end();
删除
var delSql = `delete from message where id = ${query.id}`; var delSqlParams = [query.id] connection.query(delSql, delSqlParams, function (error, results, fields) { if (error) { console.log(error); } else { console.log('The solution is: ', results); } });