NodeJS
介绍
用Javascript编写的Node.js链接Mysql数据库的驱动模块。
安装
- 包地址:
-
npm安装
<code>$ npm install mysql</code>
简单范例
<code>var mysql= require('mysql');//创建数据库连接对象var connection = mysql.createConnection({host : 'localhost',user : 'me',password : 'secret'});//打开数据库连接connection.connect();//执行数据库查询connection.query<i style="color:transparent">本文来源gaodai$ma#com搞$$代**码)网8</i>('SELECT 1 + 1 AS solution', function(err, rows, fields) {if (err) throw err;console.log('The solution is: ', rows[0].solution);});//关闭数据库连接connection.end();</code>
连接选项(Connection options)
- host:
- port:
- localAddress:
- socketPath:
- user:
- password:
- database:
- connectTimeout:
- stringifyObjects:
- insecureAuth:
- typeCast:
- queryFormat:
- supportBigNumbers:
- bigNumberStrings:
- dateStrings:
- debug:
- trace:
- multipleStatements:
- flags:
- ssl:
除了将连接选项组装为一个对象外,还可以使用URl字符串的方式定义选项,例如:
<code>var connection = mysql.createConnection('mysql://user:pass@host/db?debug=true&charset=BIG5_CHINESE_CI&timezone=-0700');</code>
提醒:连接时首先会尝试将URL字符串解析为JSON对象,如果解析失败则会当成明文字符串处理
关闭连接
可以通过两种方式关闭数据库连接。
通过end()
方法按照正常状态关闭已经完成的数据库连接。