首先在数据库中建立如下表:
js连接数据库代码如下:
var mysql = require("mysql");
//创建一个connection
var connection = mysql.createConnection({
host: 'localhost',
user: 'root',
password:'root',
database:"nodejs",
port:'3306'
});
//创建一个connection
connection.connect(function(err){
if(err){
console.log('[query] - :'+err);
return;
}
console.log('[connection connect] succeed');
});
//执行SQL语句
connection.query('select name from t_user where id=1',function(err,rows){
console.log('the solution is:',rows[0].name);
});
//关闭connection
connection.end(function(err){
if(err){
return;
}
console.log('[connection end] succeed');
})
运行结果:
![](https://img-blog.csdn.net/20160929151829614?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQv/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/Center)