Nodejs连接mysql并实现增、删、改、查操作的方法详(2)
3、运行结果
D:\User\myappejs4>node mysqltest.js 1 admin 32 2 dans88 45 3 张三 35 4 ABCDEF 88 5 李小二 65
四、Node.js结合MySQL的增、删、改、查操作
1、增
var mysql = require('mysql'); var connection = mysql.createConnection({ host : '127.0.0.1', user : 'root', password : 'root123', port: '3306', database: 'my_news_test', }); connection.connect(); var userAddSql = 'INSERT INTO node_user(id,name,age) VALUES(0,?,?)'; var userAddSql_Params = ['Wilson', 55]; //增 add connection.query(userAddSql,userAddSql_Params,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('#######################'); }); connection.end();
运行如下
D:\User\myappejs4>node mysqltestadd.js -------INSERT---------- INSERT ID: { fieldCount: 0, affectedRows: 1, insertId: 6, serverStatus: 2, warningCount: 0, message: '', protocol41: true, changedRows: 0 } #######################
2、改
var mysql = require('mysql'); var connection = mysql.createConnection({ host : '127.0.0.1', user : 'root', password : 'root123', port: '3306', database: 'my_news_test', }); connection.connect(); var userModSql = 'UPDATE node_user SET name = ?,age = ? WHERE id = ?'; var userModSql_Params = ['Hello World',99,7]; //改 up connection.query(userModSql,userModSql_Params,function (err, result) { if(err){ console.log('[UPDATE ERROR] - ',err.message); return; } console.log('----------UPDATE-------------'); console.log('UPDATE affectedRows',result.affectedRows); console.log('******************************'); }); connection.end();
运行结果如下
D:\User\myappejs4>node mysqltest_up.js ----------UPDATE------------- UPDATE affectedRows 1 ******************************
3、查操作
var mysql = require('mysql'); var connection = mysql.createConnection({ host : '127.0.0.1', user : 'root', password : 'root123', port: '3306', database: 'my_news_test', }); connection.connect(); var userGetSql = 'SELECT * FROM node_user'; //查 query connection.query(userGetSql,function (err, result) { if(err){ console.log('[SELECT ERROR] - ',err.message); return; } console.log('---------------SELECT----------------'); console.log(result); console.log('$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$'); }); connection.end();
内容版权声明:除非注明,否则皆为本站原创文章。