发布网友 发布时间:2022-04-22 01:37
共2个回答
懂视网 时间:2022-04-30 03:49
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();//记得关闭连接 });
nodejs中如何连接mysql
标签:
热心网友 时间:2022-04-30 00:57
var mysql = require('mysql');
var conn = mysql.createConnection({
host: 'localhost',
user: 'root',
password: '',
database:'nodejs',
port: 3306
});
conn.connect();
//查询
// conn.query('SELECT * from user where name="wangwei"', function(err, result) {
// if (err) throw err;
// console.log(result);
// })
//新增
// conn.query('insert into user (username,password) values("huxiaona","123456")', function(err, result) {
// if (err) throw err;
// console.log(result);
// })
//删除
// conn.query('delete from user where username="wupeigui"', function(err, result) {
// if (err) throw err;
// console.log(result);
// })
conn.query('update user set id="1" where username="huxiaona"',function(err,result){
if (err) {throw err};
console.log("修改数据成功");
})
conn.end();