用node 玩轉(zhuǎn)mysql

一、安裝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í)行查詢的方法:

  1. 普通回調(diào)
connection.query('select * from books', function (error, results, fields) {
    for(let book of results){
        console.log(book.bookName,book.price)
    }
     connection.end();
});
  1. 流式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)換

  1. 默認情況下,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.
  2. 但如果我們需要進行特殊的類型轉(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)換工作。

  1. 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.

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容