一、安裝mysql的node驅(qū)動
npm install -S mysql
二、創(chuàng)建連接的方法:
var mysql = require('mysql');
var connection = mysql.createConnection({
host : 'johnyu.cn',
user : 'john',
password : '123',
database : 'test'
});
//實際連接的同步方法
connection.connect();
官網(wǎng)中有關(guān)創(chuàng)建連接的更多的方式
三、執(zhí)行更新的方法:
let sql="insert into books ( bookName,price) values(?,?)";
let params1=['javaScript權(quán)威指南',211];
connection.query(sql,params1,function (err,result) {
if(!err){
console.log(result.insertId)//新的id值
connection.end();
}
})
四、執(zhí)行查詢的方法:
- 普通回調(diào)
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("執(zhí)行異常"))
.on('result',row=>console.log(row.bookName,row.price))
.on('end',()=>connection.end())
五、使用事務(wù)
let sql="insert into books ( bookName,price) values(?,?)";
let params1=['javaScript權(quán)威指南',211];
let params2=['JavaScript編程精粹',211];
//開啟事務(wù)的方式完成插入
connection.beginTransaction(function (err) {
connection.query(sql,params1,function (error,result) {
connection.query(sql,params2,function (error,result) {
connection.commit(function (err) {
// connection.end();
})
})
})
})
六、類型轉(zhuǎn)換
- 默認情況下,mysql驅(qū)動庫會自動的將“sql數(shù)據(jù)類型”和“nodjs數(shù)據(jù)類型”做轉(zhuǎn)換。如:
varchar,text轉(zhuǎn)換為String, Date,Timestamp轉(zhuǎn)換為Date,BLOB
BINARY轉(zhuǎn)換為Buffer. - 但如果我們需要進行特殊的類型轉(zhuǎn)換,如tiny轉(zhuǎn)換為Boolean時,我們就需要進行“類型轉(zhuǎn)換攔截器的配置”。
var connection = mysql.createConnection({
host : 'johnyu.cn',
user : 'john',
password : 'xxx',
database : 'test',
//類型轉(zhuǎn)換的定制
typeCast: function (field, next) {
if (field.type==='TINY' && field.name==='sex') {
return (field.string() === '1'); // 1 = true, 0 = false
} else {
return next();
}
}
});
connection.connect();
此時,如進行查詢或更新的操作時,就會進行相應(yīng)的轉(zhuǎn)換工作。
- 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.