nodejs怎么后台操作mysql
2017-12-06 · 百度知道合伙人官方认证企业
连接流程代码如下:
var mysql = require('mysql'); //调用MySQL模块//创建一个connectionvar connection = mysql.createConnection({
host : '127.0.0.1', //主机
user : 'root', //MySQL认证用户名
password:'12345',
port: '3306',
database: 'node'});//创建一个connectionconnection.connect(function(err){
if(err){
console.log('[query] - :'+err); return;
}
console.log('[connection connect] succeed!');
});
//执行SQL语句connection.query('SELECT 1 + 1 AS solution', function(err, rows, fields) {
if (err) {
console.log('[query] - :'+err); return;
}
console.log('The solution is: ', rows[0].solution);
});
//关闭connectionconnection.end(function(err){
if(err){
return;
}
console.log('[connection end] succeed!');
});12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
关于Connection Optionos
要想创建一个数据库连接,先就要认识清楚Options
host:主机地址 (默认:localhost)
user:用户名
password:密码
port:端口号 (默认:3306)
database:数据库名
charset:连接字符集(默认:’UTF8_GENERAL_CI’,注意字符集的字母都要大写)
localAddress:此IP用于TCP连接(可选)
socketPath:连接到unix域路径,当使用 host 和 port 时会被忽略
timezone:时区(默认:’local’)
connectTimeout:连接超时(默认:不限制;单位:毫秒)
stringifyObjects:是否序列化对象(默认:’false’ ;与安全相关https://github.com/felixge/node-mysql/issues/501)
typeCast:是否将列值转化为本地JavaScript类型值 (默认:true)
queryFormat:自定义query语句格式化方法 https://github.com/felixge/node-mysql#custom-format
supportBigNumbers:数据库支持bigint或decimal类型列时,需要设此option为true (默认:false)
bigNumberStrings:supportBigNumbers和bigNumberStrings启用 强制bigint或decimal列以JavaScript字符串类型返回(默认:false)
dateStrings:强制timestamp,datetime,data类型旅液以字符串类型返回,而不是JavaScript Date类型(默认:false)
debug:开启调试(默认:false)
multipleStatements:是否许一个query中有多个MySQL语句 (默认:false)
flags:用于修改连接标志,更多详情:https://github.com/felixge/node-mysql#connection-flags
ssl:使用ssl参数(与crypto.createCredenitals参数格式一至)或一个包含ssl配置文件名称的字符串,目前只捆绑Amazon RDS的配置文件
其它:
可以使用URL形式的加接字符串,不多介绍了,不太喜欢那种格式敬备,觉得可读性差,也易出错,想了解的可以去主页上看拆稿物。
MYSQL CURD操作
增加
var mysql = require('mysql');var DATABASE = "seckill";var TABLE="seckill"var connection = mysql.createConnection({
host:'127.0.0.1',
user:'root',
password:'12345',
port:'3306',
database: DATABASE
});
connection.connect();var addVip = 'insert into seckill(name,number) values(?,?)';var param = ['100元秒杀家教机',100];
connection.query(addVip, param, function(error, result){
if(error)
{
console.log(error.message);
}else{
console.log('insert id: '+result.insertId);
}
});
connection.end();12345678910111213141516171819202122232425
删除
var mysql = require('mysql');var DATABASE = "node";var TABLE="seckill"var connection = mysql.createConnection({
host:'127.0.0.1',
user:'root',
password:'12345',
port:'3306',
database: DATABASE
});
connection.connect();var addVip = 'delete from seckill where seckill_id = 1005';
connection.query(addVip, function(error, result){
if(error)
{
console.log(error.message);
}else{
console.log('affectedRows: '+result.affectedRows);
}
});
connection.end();123456789101112131415161718192021222324
查找
var mysql = require("mysql");var DATABASE = "node";var TABLE="seckill"var connection = mysql.createConnection({
host:'127.0.0.1',
user:'root',
password:'12345',
port:'3306',
});
connection.connect();
connection.query('use '+DATABASE);
connection.query('select * from '+TABLE, function(error, results, fields){
if (error) { throw error;
} if (results) { for(var i = 0; i < results.length; i++)
{
console.log('%s\t%s',results[i].name,results[i].end_time);
}
}
});
connection.end();12345678910111213141516171819202122232425
修改
var mysql = require('mysql');var DATABASE = "seckill";var connection = mysql.createConnection({
host:'127.0.0.1',
user:'root',
password:'12345',
port:'3306',
database: DATABASE
});
connection.connect();var userSql = "update seckill set number = number-1 where seckill_id = ?";var param = [1000, 2];
connection.query(userSql, param, function (error, result) {
if(error)
{
console.log(error.message);
}else{
console.log('affectedRows: '+result.affectedRows);
}
});
connection.end();123456789101112131415161718192021
结束连接其实有两种方法end(),destory();
end()
end()方法在queries都结束后执行,end()方法接收一个回调函数,queries执行出错,仍然后结束连接,错误会返回给回调函数err参数,可以在回调函数中处理!destory()
比较暴力,没有回调函数,即刻执行,不管queries是否完成!- DROP PROCEDURE IF EXISTS `P_SeckillInfo`;DELIMITER ;;CREATE DEFINER=`root`@`localhost` PROCEDURE `P_SeckillInfo`(IN ExtName VARCHAR(120),IN ExtNumber INT(11),OUT ExtReturnVal INT)
- TOP: BEGIN
- DECLARE EXIT HANDLER FOR SQLEXCEPTION BEGIN
- ROLLBACK;
- SET ExtReturnVal = 0; -- Failed
- END;
- START TRANSACTION;
- INSERT INTO seckill(name, number) VALUES(ExtName,ExtNumber);
- SET ExtReturnVal = 1;
- SELECT ExtReturnVal;
- COMMIT;END;;
- DELIMITER ;12345678910111213141516171819202122232425262728293031323334
- var mysql = require("mysql");var pool = mysql.createPool({
- host: '127.0.0.1',
- user: 'root',
- password:'12345',
- port:'3306',
- database:'node'});//监听connection事件pool.on('connection', function(connection) {
- connection.query('select * from seckill', function(error, results, fields){
- if (error) { throw error;
- } if (results) { for(var i = 0; i < results.length; i++)
- {
- console.log('%s\t%s',results[i].name,results[i].end_time);
- }
- }
- });
- });//连接池可以直接使用,也可以共享一个连接或管理多个连接(引用官方示例)//直接使用pool.query('SELECT 1 + 1 AS solution', function(err, rows, fields) {
- if (err) throw err;
- console.log('The solution is: ', rows[0].solution);
- });//共享连接function myQuery(sql){
- pool.getConnection(function(err, connection) {
- connection.query(sql, function(err, result) {
- console.log(result); //释放连接
- connection.release();
- }); //Error: Connection already released,应该每次到连接池中再次获取
- // connection.query( 'SELECT * FROM seckill;', function(err, result) {
- // console.log(result);
- // connection.release();
- // });
- });
- }
- myQuery('SELECT * FROM seckill;');
- myQuery('SELECT * FROM seckill;');123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
waitForConnections
connectionLimit
连接数限制,默认:10queueLimit
最大连接请求队列限制,设置为0表示不限制,默认:0- var mysql = require('mysql');var db_config = {
- host: '127.0.0.1',
- user: 'root',
- password:'12345',
- port:'3306',
- database:'node'};var connection;function handleDisconnect() {
- connection = mysql.createConnection(db_config);
- connection.connect(function(err) {
- if(err) {
- console.log('进行断线重连:' + new Date());
- setTimeout(handleDisconnect, 2000); //2秒重连一次
- return;
- }
- console.log('连接成功');
- });
- connection.on('error', function(err) {
- console.log('db error', err); if(err.code === 'PROTOCOL_CONNECTION_LOST') {
- handleDisconnect();
- } else {
- throw err;
- }
- });
- }
- handleDisconnect();12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
- var mysql = require('mysql');var pool = mysql.createPool({
- host: '127.0.0.1',
- user: 'root',
- password:'12345',
- port:'3306',
- database:'node'});function myQuery(sql){
- pool.getConnection(function(err,connection){
- connection.query(sql,function(err,result){
- //console.log(err);
- console.log(result);
- connection.release();
- }); // connection.query('SELECT * FROM userinfo WHERE id = ' + pool.escape('5 OR ID = 6') ,function(err,result){
- // //console.log(err);
- // console.log(result);
- // connection.release();
- // });
- });
- }
- myQuery('SELECT * FROM seckill WHERE seckill_id = ' + '1006 OR seckill_id = 1007');
- myQuery('SELECT * FROM seckill WHERE seckill_id = ' + pool.escape('1006 OR seckill_id = 1007'));123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
使用连接池
在数据库中执行如下代码创建一个存储过程
调用示例:
1.连接池的创建,使用createPool方法,options和createConntion一致;
2.其它连接池配置选项
当连接池没有连接或超出最大限制时,设置为true且会把连接放入队列,设置为false会返回error
断开重连
示例代码:
首先关闭mysql服务,然后执行程序,会一直打印断线重连,当再次开启mysql服务后,打印连接成功。
防止SQL注入
可以使用pool.escape()和connect.escape(),示例代码:
结果可以看出,第1个query拼接条件可以被执行,而通过escape方法转义后的忽略了后面的拼接的部分!
遇到的问题
编码导致的问题
1366 (HY000): Incorrect string value: ‘\xC3\xEB\xC9\xB1’ for column ‘ExtName’ at row 1
字符编码没有统一的问题,查看数据库的编码方式命令为:
mysql> show variables like ‘character%’;
从以上信息可知数据库的编码为latin1,需要修改为gbk或者是utf8;