nodejs怎么连接数据库mysql
发布网友
发布时间:2022-04-07 22:30
我来回答
共3个回答
懂视网
时间:2022-04-08 02:51
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-07 23:59
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();
热心网友
时间:2022-04-08 01:17
npm install knex@0.6 --save
npm install mysql
var knex = require('knex')({
client: 'mysql',
connection: {
host : '<a href="https://www.baidu.com/s?wd=127.0.0.1&tn=44039180_cpr&fenlei=mv6quAkxTZn0IZRqIHckPjm4nH00T1YkPjF-Pj9hmHcvPjbANB0ZwV5Hcvrjm3rH6sPfKWUMw85HfYnjn4nH6sgvPsT6KdThsqpZwYTjCEQLGCpyw9Uz4Bmy-bIi4WUvYETgN-TLwGUv3EPjbvrH0vrHmknWmznj0Yrj0Y" target="_blank" class="-highlight">127.0.0.1</a>',
user : 'your_database_user',
password : 'your_database_password',
database : 'myapp_test'
}
});
knex.select('title', 'author', 'year').from('books').then(function(data){
//取到的数据
console.log(data)
})
更多:
http://knexjs.org/