node mysql增删改查

稳定版 : npm install mysql --save
安装最新版本: npm install felixge/node-mysql

连接数据库

var mysql = require("mysql");
 
var connection = mysql.createConnection({
  host: 'localhost',
  user: 'root',
  password: 'pwd',
  port: 3306,//端口
  database: '数据库名'
});

关闭数据库连接,请求结束应当关闭

connection.end(function(err) {});//已添加sql语句不会结束

connection.destroy();//销毁,方法会即刻执行,没有callback
//增删改查的一些回调数据
result.insertId;//插入有自增主键的表,可以这样获得插入的ID:
result.affectedRows;//插入,更新或删除语句受影响的行数
result.changedRows ;//更新语句被改变的行数。
connection.threadId;//获取MySQL连接ID(“thread ID”)。

var usr={name:'x',password:'pwd',mail:'[email protected]'};
connection.query('insert into users set ?', usr, function(err, result) {
    if (err) throw err;
    console.log(result,result.insertId);//result.insertId插入行id

});

connection.query('delete from  users where name="x"', function(err, result) {
    if (err) throw err;
    console.log(result);
});

connection.query('UPDATE users SET foo = ?, bar = ? WHERE id = ?', ['a', 'b', '1'], function (error, results, fields) {
  if (error) throw error;
  // ... 
});

#ORDER BY `time`(或其他字段) DESC(倒序,ASC正序(默认))

//1.普通方法
connection.query('select * from users where name="x"  and `pwd`= "123"', function(err, rows, fields) {
    if (err) throw err;
    for(var i= 0,usr;usr=rows[i++];){
        console.log('user nae='+usr.name + ', password='+usr.password);
    }
});

//2.占位符 .query(sqlString, values, callback)
connection.query({sql: 'SELECT * FROM `books` WHERE `x` = ?' },['David'],function (error, results, fields) {

});

//3. .query(options,values,callback):values会覆盖options.values
connection.query({
    sql: 'SELECT * FROM `books` WHERE `author` = ?',
    timeout: 40000, // 40s
    values:['David'],
  },  ['David'],  function (error, results, fields) {

  }
);

//4. ??,应该是进行编码
var userId = 1;
var columns = ['username', 'email'];
var query = connection.query('SELECT ?? FROM ?? WHERE id = ?', [columns, 'users', userId], function(err, results) {
  // ...
});
console.log(query.sql); // SELECT `username`, `email` FROM `users` WHERE id = 1

防止SQL注入, 对用户提供的数据插入查询语句前应该总是对其进行编码 。

mysql.escape(), 
connection.escape(),
pool.escape()

var sql = 'SELECT * FROM users WHERE id = ' + connection.escape(userId);

占位符默认使用connection.escape()

err:

err.code: 
err.fatal: 布尔值, 指出这个错误是否是终端连接对象。

//监听错误
connection.on('error', function(err) {
  console.log(err.code); // 'ER_BAD_DB_ERROR'
});
var express = require("express");
var mysql = require("mysql");
var server = express();

function mysqlFn(){
    var sql = mysql.createConnection({
        host: 'tk.cn',
        user: 'root',
        password: '',
        database: 'data',
        port: 3306
    })
    sql.connect();
    return sql
}
server.get("/", function(req, res) {
    var sql=mysqlFn();
        sql.query("SELECT * FROM `h` ORDER BY id DESC", function(err, rows, fields) {//"SELECT * FROM `h` where id=1 ORDER BY id DESC"
        if (err) {
            console.log(err);
             res.end();
        } else {
            res.header("charset", "utf-8");
            res.send(rows);
            sql.end();
            console.log(rows);
        }
    });
})
server.get("/set", function(req, res) {
    var sql=mysqlFn();
        sql.query("update `h` set name = 'x' where id=1", function(err, rows, fields) {
        if (err) {
            console.log(err);
            res.end();
        } else {
            res.header("charset", "utf-8");
            res.send(rows);
            sql.end();
//{"fieldCount":0,"affectedRows":1,"insertId":0,"serverStatus":2,"warningCount":0,"message":"(Rows matched: 1  Changed: 1  Warnings: 0","protocol41":true,"changedRows":1}
            console.log(rows);
        }
       
    });
})
server.get("/del", function(req, res) {
   var sql=mysqlFn();
        sql.query("delete from h where name='h' ", {},function(err, rows, fields){
        if (err) {
            console.log(err);
            res.end();
        } else {//"affectedRows":2,行数
// {"fieldCount":0,"affectedRows":2,"insertId":0,"serverStatus":34,"warningCount":0,"message":"","protocol41":true,"changedRows":0}
            res.header("charset", "utf-8");
            res.send(rows);
            sql.end();
            console.log(rows);
        }
    })
})
server.get("/insert", function(req, res) {
    var sql=mysqlFn();
        sql.query("insert into h set ?", {
        "name": "h"
    }, function(error, results, fields) {
        if (error) {
            res.send(error);
        } else {
            res.send(results);
            sql.end();
// {"fieldCount": 0,"affectedRows": 1,"insertId": 4,"serverStatus": 2,"warningCount": 0,"message": "","protocol41": true,"changedRows": 0}
        }
    })
})
server.listen(8080);

原文:http://blog.csdn.net/huangxiongbiao/article/details/46116901

你可能感兴趣的:(node mysql增删改查)