nodejs 操作mysql
程序员文章站
2022-07-10 16:10:36
...
1、安装mysql模块
2、新建mysql连接
const mysql = require('mysql');
const connection = mysql.createConnection({
host: 'localhost',
user: 'root',
password: '12345678',
database: 'test'
});
connection.connect(function(){
console.log('connect success')
});
3、执行查询语句
const mysql = require('mysql');
const connection = mysql.createConnection({
host: 'localhost',
user: 'root',
password: '12345678',
database: 'test'
});
connection.connect(function(){
console.log('connect success')
});
connection.query("select * from users", function(err, result, fields){
if(err) throw err;
for(let i = 0; i < result.length; i++){
console.log('名称:' + result[i].username);
console.log('密码:' + result[i].password);
}
});
connection.end();
4、插入数据
const insertSql = 'insert into users (username, password) values (?, ?)';
const sqlParam = ['白骨精', '123456'];
connection.query(insertSql, sqlParam, function(err, result){
if(err)throw err;
console.log('insert success');
console.log(JSON.stringify(result));
});
5、删除数据
connection.query("delete from users where id = ?", [6], function(err, result){
if(err)throw err;
console.log('delete success');
});
6、更新数据
connection.query("update users set password = ? where id = ?", ['wang', 3], function(err, result){
if(err) throw err;
console.log('更新成功');
});