Node.js入门(8)之Mysql模块
参考 http://blog.csdn.net/a1104258464/article/details/52115808
安装依赖模块
先新建express自动生成项目$ express mysql-test -c
。
然后安装依赖模块
$npm install
&$npm install mysql --save
。
使用
在router文件夹下建立mysql.js模块文件
var db = {};
var mysql = require('mysql');
var user={
host: '10.81.36.167', //地址
user: 'root', //用户名
password: '123456', //密码
database: 'nodejs' //数据库
}
//创建连接
var connection = mysql.createConnection(user);
//查询
db.query = function (sql, callback) {
connection.query(sql, function (err, rows, fields) {
if (err) {
console.log(err);
callback(err, null);
return;
};
callback(null, rows, fields);
});
}
module.exports = db;
调用SQL语句
修改index.js
var db = require('./mysql.js');
router.get('/add', function(req, res, next) {
var sql = `insert into users (name,age) values ("丫头",16) `;
db.query(sql ,function(err,rows,fields){
if (err) {
console.log(err);
return;
}
console.log("插入成功");
console.log(rows)
})
});
SQL常用语句
sql的指令格式:所有sql指令都是以分号(;)结尾,两个减号(–)则表示注释。
创建新表:create table tabname(col1 type1 [not null] [primary key],col2 type2 [not null],..)
选择:select * from table1 where 范围
插入:insert into table1(field1,field2) values(value1,value2)
删除:delete from table1 where 范围
更新:update table1 set field1=value1 where 范围
查找:select * from table1 where field1 like ’%value1%’
—like的语法很精妙,查资料!
排序:select * from table1 order by field1,field2 [desc]
总数:select count as totalcount from table1
求和:select sum(field1) as sumvalue from table1
平均:select avg(field1) as avgvalue from table1
最大:select max(field1) as maxvalue from table1
最小:select min(field1) as minvalue from table1