Nodejs操作MySQL資料庫

來源:互聯網
上載者:User

標籤:sts   地方   blog   use   console   參數   return   temp   title   

  如何用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();    });}

 

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

 

 

 

     

Nodejs操作MySQL資料庫

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.