Nodejs操作MySQL數據庫


https://github.com/mysqljs/mysql

 

  如何用nodejs操作MySql數據呢,其實寫法還是簡單的,

     1.開始在你的node項目中 npm install mysql --save

     2.在你的新建項目中 引入代碼

      

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

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

 

   最好不好是用root 會產生沖突

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

       查詢

 

     

復制代碼
// 查找
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();
}
復制代碼

     添加

復制代碼
//添加
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'
}
復制代碼

  修改

復制代碼
//修改
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();

}
復制代碼

  刪除

 

復制代碼
//刪除
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();

    });

}
復制代碼

 

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

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM