一、安装mysql的node驱动
npm install -S mysql
二、创建连接的方法:
var mysql = require('mysql');
var connection = mysql.createConnection({
host : 'johnyu.cn',
user : 'john',
password : '123',
database : 'test'
});
//实际连接的同步方法
connection.connect();
三、执行更新的方法:
let sql="insert into books ( bookName,price) values(?,?)";
let params1=['javaScript权威指南',211];
connection.query(sql,params1,function (err,result) {
if(!err){
console.log(result.insertId)//新的id值
connection.end();
}
})
四、执行查询的方法:
- 普通回调
connection.query('select * from books', function (error, results, fields) {
for(let book of results){
console.log(book.bookName,book.price)
}
connection.end();
});
- 流式API
connection.query('select * from books')
.on('error',(error)=>console.log("执行异常"))
.on('result',row=>console.log(row.bookName,row.price))
.on('end',()=>connection.end())
五、使用事务
let sql="insert into books ( bookName,price) values(?,?)";
let params1=['javaScript权威指南',211];
let params2=['JavaScript编程精粹',211];
//开启事务的方式完成插入
connection.beginTransaction(function (err) {
connection.query(sql,params1,function (error,result) {
connection.query(sql,params2,function (error,result) {
connection.commit(function (err) {
// connection.end();
})
})
})
})
六、类型转换
- 默认情况下,mysql驱动库会自动的将“sql数据类型”和“nodjs数据类型”做转换。如:
varchar,text转换为String, Date,Timestamp转换为Date,BLOB
BINARY转换为Buffer. - 但如果我们需要进行特殊的类型转换,如tiny转换为Boolean时,我们就需要进行“类型转换拦截器的配置”。
var connection = mysql.createConnection({
host : 'johnyu.cn',
user : 'john',
password : 'xxx',
database : 'test',
//类型转换的定制
typeCast: function (field, next) {
if (field.type==='TINY' && field.name==='sex') {
return (field.string() === '1'); // 1 = true, 0 = false
} else {
return next();
}
}
});
connection.connect();
此时,如进行查询或更新的操作时,就会进行相应的转换工作。
- field操作可以使用:
db - a string of the database the field came from.
table - a string of the table the field came from.
name - a string of the field name.
type - a string of the field type in all caps.
length - a number of the field length, as given by the database.
.string() - parse the field into a string.
.buffer() - parse the field into a Buffer.
.geometry() - parse the field as a geometry value.
网友评论