nodejs中如何连接mysql,下面给出一个小Demo.
第一步安装mysql模块
npm install mysql
第二步导入mysql模块
var mysql = require('mysql');
第三步连接mysql数据库
var connection = mysql.createConnection({
host:'localhost',
user:'root',
password:'',
database:'yudi'
});
connection.connect();
第四步执行一条查询语句
var sql = "select * from person where name='"+username+"'";
connection.query(sql,function(err,rows,fields){
if(err)
console.log(err);
else{
console.log(rows);
}
//记得关闭连接
connection.end();
});
err:是错误信息
rows:查询的信息
fields:返回所有信息
下面是小Demo
var mysql = require('mysql');
var connection = mysql.createConnection({
host:'localhost',
user:'root',
password:'',
database:'yudi'
});
connection.connect();
var username = 'stu2';
var sql = "select * from person where name='"+username+"'";
connection.query(sql,function(err,rows,fields){
if(err)
console.log(err);
else{
console.log(rows);
}
connection.end();//记得关闭连接
});