Node.js-简单操作Mysql数据库

安装:
- npm install --save mysql
//引入mysql相关的包
var mysql = require(‘mysql’);
//建立相关连接
var connection = mysql.createConnection({
//主机地址: (默认:localhost)
host: ‘127.0.0.1’,
//数据库系统含有的用户
user: ‘zzzzz’,
//响应用户密码
password: ‘xxxxxxx’,
//数据库名称
database: ‘yyy’,
});
//连接数据库
connection.connect();
//数据库的查询语句
connection.query(‘SELECT * FROM student‘,function(error,results,fields){
if(error) throw(error);
console.log(’-------------------------------------Select-----------------------------------’);
console.log(‘The results is:’ , results);
console.log(’-------------------------------------Select-----------------------------------’);

});
//CURD
var AddSql = “Insert into student (Sno,Sname ,Age,Addr,Sex) values(‘19125011049’,‘Alin’,20,‘sgu’,‘female’)”;
//添加
// connection.query(AddSql,function(error,result){
// if(error){
// console.log(’[INSERT ERROR]: ’ + error.message);
// }else{
// console.log(’-------------------------------------------------INSERT-----------------------------------------’);
// console.log(‘Insert content: ’ + result);
// console.log(’-------------------------------------------------INSERT-----------------------------------------’);
// }
// });
//更新数据
var modSql = “UPDATE Student SET Age = Age + 10 WHERE Sex = ‘male’”;
connection.query(modSql,function(error,result){
if(error){
console.log(’[Update ERROR]’ + error.message);
}else{
console.log(‘After update:’+ result.affectedRows);
}
});
//删除数据
// var DelSql = “delete from student where Sno = 19126”;
// connection.query(DelSql,function(error,result){
// if(error){
// console.log(’[Delet Error]’ + error.message);
// }else{
// console.log(‘After delete:’ + result.affectedRows);
// }
// });
//关闭连接
connection.end();

你可能感兴趣的:(mysql,node.js)