电竞比分网-中国电竞赛事及体育赛事平台

分享

Nodejs操作MySQL數(shù)據(jù)庫

 條山石頭 2019-08-26

  如何用nodejs操作MySql數(shù)據(jù)呢,其實(shí)寫法還是簡單的,

     1.開始在你的node項(xiàng)目中 npm install mysql --save

     2.在你的新建項(xiàng)目中 引入代碼

      

復(fù)制代碼
//引入數(shù)據(jù)庫
var mysql=require('mysql');

//實(shí)現(xiàn)本地鏈接
var connection = mysql.createConnection({
    host: 'localhost',
    user: 'yf',
    password: '123456',
    database: 'yf'
})
復(fù)制代碼

 

   最好不好是用root 會產(chǎn)生沖突

 3. 之后就是增刪改查啦,附上代碼

       查詢

 

     

復(fù)制代碼
// 查找
function select() {
    connection.connect(function (err) {
        if (err) {
            console.error('error connecting:' + err.stack)
        }
        console.log('connected as id ' + connection.threadId);
    })

    connection.query('SELECT * FROM demo', function (error, results, fields) {
        if (error) throw error;
        console.log('The solution is:', results);
    });
    connection.end();
}
復(fù)制代碼

     添加

復(fù)制代碼
//添加
function add() {
    let post = {
        id: 1,
        name: 'Hello MySql',
        age: 20,
        time: Date.now(),
        temp: 'deom'
    };
    let query = connection.query("INSERT INTO demo SET ?", post, function (error, results, fields) {
        if (error) throw error;
    })
    console.log(query.sql); //INSERT INTO posts 'id'=1, 'title'='Hello MySQL'
}
復(fù)制代碼

  修改

復(fù)制代碼
//修改
function updeate() {
    connection.connect(function (err) {
        if (err) {
            console.error('error connecting:' + err.stack);
        }
        console.log('connected as id ' + connection.threadId);
    });

    connection.query('UPDATE demo SET name=?where id?', ['update', 1], function (error, results, fields) {
        if (error) throw error;
        console.log('changed:' + results.changeRows + 'rows');
    });

    connection.end();

}
復(fù)制代碼

  刪除

 

復(fù)制代碼
//刪除
function deletes() {
    connection.connect(function (err) {
        if (err) {
            console.error('error connecting:' + err.stack);
            return;
        }
        connection.query('DELETE FROM demo SET where id=?', [ 1], function (error, results, fields) {
            if (error) throw error;
            console.log('deleted:' + results.affectedRows + 'rows');
        });
        console.log('connected as id ' + connection.threadId);
        connection.end();

    });

}
復(fù)制代碼

 

  是不是很簡單啊 只要在你需要的地方添加方法名和對應(yīng)的參數(shù) ,就可以了

 

 

 

     

    本站是提供個(gè)人知識管理的網(wǎng)絡(luò)存儲空間,所有內(nèi)容均由用戶發(fā)布,不代表本站觀點(diǎn)。請注意甄別內(nèi)容中的聯(lián)系方式、誘導(dǎo)購買等信息,謹(jǐn)防詐騙。如發(fā)現(xiàn)有害或侵權(quán)內(nèi)容,請點(diǎn)擊一鍵舉報(bào)。
    轉(zhuǎn)藏 分享 獻(xiàn)花(0

    0條評論

    發(fā)表

    請遵守用戶 評論公約

    類似文章 更多