都市烟火通过本文主要向大家介绍了node连接mysql,node mysql,node.js mysql,node express mysql,node操作mysql等相关知识,希望对您有所帮助,也希望大家支持linkedu.com www.linkedu.com
本文实例讲述了node操作mysql数据库的方法。分享给大家供大家参考,具体如下:
1、建立数据库连接:createConnection(Object)
方法
该方法接受一个对象作为参数,该对象有四个常用的属性host,user,password,database。与php中链接数据库的参数相同。属性列表如下:
host | 连接数据库所在的主机名. (默认: localhost) |
port | 连接端口. (默认: 3306) |
localAddress | 用于TCP连接的IP地址. (可选) |
socketPath | 链接到unix域的路径。在使用host和port时该参数会被忽略. |
user | MySQL用户的用户名. |
password | MySQL用户的密码. |
database | 链接到的数据库名称 (可选). |
charset | 连接的字符集. (默认: 'UTF8_GENERAL_CI'.设置该值要使用大写!) |
timezone | 储存本地时间的时区. (默认: 'local') |
stringifyObjects | 是否序列化对象. See issue #501. (默认: 'false') |
insecureAuth | 是否允许旧的身份验证方法连接到数据库实例. (默认: false) |
typeCast | 确定是否讲column值转换为本地JavaScript类型列值. (默认: true) |
queryFormat | 自定义的查询语句格式化函数. |
supportBigNumbers | 数据库处理大数字(长整型和含小数),时应该启用 (默认: false). |
bigNumberStrings | 启用 supportBigNumbers和bigNumberStrings 并强制这些数字以字符串的方式返回(默认: false). |
dateStrings | 强制日期类型(TIMESTAMP, DATETIME, DATE)以字符串返回,而不是一javascript Date对象返回. (默认: false) |
debug | 是否开启调试. (默认: false) |
multipleStatements | 是否允许在一个query中传递多个查询语句. (Default: false) |
flags | 链接标志. |
还可以使用字符串连接数据库例如:
var connection = mysql.createConnection('mysql://user:pass@host/db?debug=true&charset=BIG5_CHINESE_CI&timezone=-0700');</div>
2、结束数据库连接end()
和destroy()
end()接受一个回调函数,并且会在query结束之后才触发,如果query出错,仍然会终止链接,错误会传递到回调函数中处理。
destroy()立即终止数据库连接,即使还有query没有完成,之后的回调函数也不会在触发。
3、创建连接池 createPool(Object)
Object和createConnection参数相同。
可以监听connection事件,并设置session值
pool.on('connection', function(connection) { connection.query('SET SESSION auto_increment_increment=1') });</div>
connection.release()释放链接到连接池。如果需要关闭连接并且删除,需要使用connection.destroy()
pool除了接受和connection相同的参数外,还接受几个扩展的参数
createConnection | 用于创建链接的函数. (Default: mysql.createConnection) |
waitForConnections | 决定当没有连接池或者链接数打到最大值时pool的行为. 为true时链接会被放入队列中在可用是调用,为false时会立即返回error. (Default: true) |
connectionLimit | 最大连接数. (Default: 10) |
queueLimit | 连接池中连接请求的烈的最大长度,超过这个长度就会报错,值为0时没有限制. (Default: 0) |
4、连接池集群
允许不同的host链接
// create var poolCluster = mysql.createPoolCluster(); poolCluster.add(config); // anonymous group poolCluster.add('MASTER', masterConfig); poolCluster.add('SLAVE1', slave1Config); poolCluster.add('SLAVE2', slave2Config); // Target Group : ALL(anonymous, MASTER, SLAVE1-2), Selector : round-robin(default) poolCluster.getConnection(function (err, connection) {}); // Target Group : MASTER, Selector : round-robin poolCluster.getConnection('MASTER', function (err, connection) {}); // Target Group : SLAVE1-2, Selector : order // If can't connect to SLAVE1, return SLAVE2. (remove SLAVE1 in the cluster) poolCluster.on('remove', function (nodeId) { console.log('REMOVED NODE : ' + nodeId); // nodeId = SLAVE1 }); poolCluster.getConnection('SLAVE*', 'ORDER', function (err, connection) {}); // of namespace : of(pattern, selector) poolCluster.of('*').getConnection(function (err, connection) {}); var pool = poolCluster.of('SLAVE*', 'RANDOM'); pool.getConnection(function (err, connection) {}); pool.getConnection(function (err, connection) {}); // destroy poolCluster.end();</div>
链接集群的可选参数
canRetry | 值为true时,允许连接失败时重试(Default: true) |
removeNodeErrorCount | 当连接失败时 errorCount 值会增加. 当errorCount 值大于 removeNodeErrorCount 将会从PoolCluster中删除一个节点. (Default: 5) |
defaultSelector | 默认选择器. (Default: RR) |
RR | 循环. (Round-Robin) |
RANDOM | 通过随机函数选择节点. |
ORDER | 无条件地选择第一个可用节点. |
5、切换用户/改变连接状态
Mysql允许在比断开连接的的情况下切换用户
connection.changeUser({user : 'john'}, function(err) { if (err) throw err; });</div>
参数
user | 新的用户 (默认为早前的一个). |
password | 新用户的新密码 (默认为早前的一个). |
charset | 新字符集 (默认为早前的一个). |
database | 新数据库名称 (默认为早前的一个). |
6、处理服务器连接断开
var db_config = { host: 'localhost', user: 'root', password: '', database: 'example' }; var connection; function handleDisconnect() { connection = mysql.createConnection(db_config); // Recreate the connection, since // the old one cannot be reused. connection.connect(function(err) { // The server is either down if(err) { // or restarting (takes a while sometimes). console.log('error when connecting to db:', err); setTimeout(handleDisconnect, 2000); // We introduce a delay before attempting to reconnect, } // to avoid a hot loop, and to allow our node script to }); // process asynchronous requests in the meantime. // If you're also serving http, display a 503 error. connection.on('error', function(err) { console.log('db error', err); if(err.code === 'PROTOCOL_CONNECTION_LOST') { // Connection to the MySQL server is usually handleDisconnect(); // lost due to either server restart,