node操作mysql

第一步:引入mysql模块

var mysql = require('mysql');

第二步:建立连接

var connection = mysql.createConnection(
{
        host:'localhost',
        user: 'root',
        password: 'Gepoint',
        database: 'mqtt'
});
connection.connect();

第三步:执行sql操作

var sql = 'SELECT * FROM user';
var sql_insert = "insert into user(userid, username, userpass)" +
    "values('1151301118', 'ljabo', '123321')";
connection.query(sql_insert)

var sql_update = "UPDATE USER SET userpass = ? WHERE id = ? ";

var mysqlParms = ['gggg3', '2'] 

connection.query(sql_update, mysqlParms)

connection.query(sql,function (err, result) {
    if(err){
      console.log('[SELECT ERROR] - ', err.message);
      return;
    }

    console.log('-----------------------SELECT-------------------------');
    console.log(result);

    console.log('--------------------------------------------------\n\n'); 
    console.log('-----------------------SELECT ONE---------------------------'); 
    console.log(result[2]);

    console.log(typeof (result))
});

第四步:关闭连接

connection.end();