安装mysql依赖
$install npm mysql
createConnection:连接
host:主机地址
user: 用户名
password: 密码
database: 数据库名称
conmysql文件
导入模块 设置基础信息
var client = require('mysql').createConnection({
host:'localhost',
user:'root',
password:'',
database:'nodesql'
});
增删改查
function disposeData(sql) {
client.query(sql,function (error,result) {
if(error){
console.log('操作失败');
return;
}
console.log('操作成功');
console.log(result);
})
}
//增
var insertData = 'insert into myclass value (null,"web",1,88.88,45) ';
//删
var deleteData = 'delete from myclass where name="jean"'
//改
var updataData = 'update myclass set sex = 1 where id=4 '
//查
client.query('select * from myclass ',function (error,result) {
if(error) throw error;
console.log("成功");
if(result.length){
for(var i= 0; i<result.length;i++){
console.log(result[i].name);
}
}
disposeData(insertData);
disposeData(deleteData);
disposeData(updataData);
参数传递
-
向query传递第二个参数 类型为数组 数组内容和sql语句中的?一一对应
client.query(sql,Array('li',1,33,3),function(error,result){ if(error) throw error; console.log('操作成功'); }); var canshusql = 'insert into myclass values(null,?,?,?,?)'