连接选项(Connection 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列以java script字符串类型返回(默认:false)
dateStrings:强制timestamp,datetime,data类型以字符串类型返回,而不是java script 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形式的加接字符串,不多介绍了,不太喜欢那种格式,觉得可读性差,也易出错,想了解的可以去主页上看。
关闭连接
可以通过两种方式关闭数据库连接。
通过 end() 方法按照正常状态关闭已经完成的数据库连接:
connection.end(function(err) {
// The connection is terminated now
});
另外一种可选的方法是通过 destroy() 方法
这种方法会即刻执行,不管queries是否完成!
connection.destroy();
与 end() 不同的是, destroy() 方法不接受callback
查询
建立一个查询的最基本的方法是在一个连接实例(像Connection, Pool, PoolNamespace 或其他相似的对象)上调用 .query() 方法
query() 最简单的形式是 .query(sqlString, callback), 第一个参数是SQL语句,第二个参数是回调函数:
connection.query('SELECT * FROM `books` WHERE `author` = "David"', function (error, results, fields) {
// error will be an Error if one occurred during the query
// results will contain the results of the query
// fields will contain information about the returned results fields (if any)
});
第二种形式 .query(sqlString, values, callback) 使用了占位符:
connection.query('SELECT * FROM `books` WHERE `author` = ?', ['David'], function (error, results, fields) {
// error will be an Error if one occurred during the query
// results will contain the results of the query
// fields will contain information about the returned results fields (if any)
});
第三种形式 .query(options, callback) 是在查询中使用多种选项参数, 如 escaping query values,joins with overlapping column names,timeouts, 和type casting:
connection.query({
sql: 'SELECT * FROM `books` WHERE `author` = ?',
timeout: 40000, // 40s
values: ['David']
}, function (error, results, fields) {
// error will be an Error if one occurred during the query
// results will contain the results of the query
// fields will contain information about the returned results fields (if any)