NodeJS + MySQL 入门实例

来源(博客园)

From: http://www.cnblogs.com/tinyphp/p/4931336.html

NodeJS + MySQL 入门实例

此前我已准备好mysql,使用的是PHP的组合包Appserv

手动添加数据库依赖:

在package.json的dependencies中新增,

"mysql": "latest",
{
	"name": "news",
	"version": "0.0.0",
	"private": true,
	"scripts": {
		"start": "node ./bin/www"
	},
	"dependencies": {
		"body-parser": "~1.13.2",
		"cookie-parser": "~1.3.5",
		"debug": "~2.2.0",
		"express": "~4.13.1",
		"jade": "~1.11.0",
		"morgan": "~1.6.1",
		"serve-favicon": "~2.3.0",
		"mysql":"latest"
	}
}


然后使用命令:

npm install


或使用命令安装mysql并添加依赖:

npm install mysql -save




官方例子:

//连接数据库
var mysql = require('mysql');
var connection = mysql.createConnection({
		host: '数据库地址如:localhost',
		user: '数据库用户名',
		password: '密码',
		database:'数据库名'
});

connection.connect();
//查询
connection.query('SELECT 1 + 1 AS solution', function(err, rows, fields) {
		if (err) throw err;
		console.log('The solution is: ', rows[0].solution);
});
//关闭连接
connection.end();


运行node



这样Nodejs连接上了MySQL

可是这样真的就连上了吗?还是弄个表出来查下比较妥,下面在数据库:test下创建一个表名为:mytable

--
-- 数据库: `test`
--

-- --------------------------------------------------------

--
-- 表的结构 `mytable`
--

CREATE TABLE `mytable` (
	`name` varchar(255) NOT NULL
) ENGINE=MyISAM DEFAULT CHARSET=utf8;

--
-- 导出表中的数据 `mytable`
--

INSERT INTO `mytable` VALUES ('名称1');
INSERT INTO `mytable` VALUES ('名称2');


修改上面例子的查询语句

//连接数据库
var mysql = require('mysql');
var connection = mysql.createConnection({
		host: 'localhost',
		user: 'root',
		password: 'open00',
		database:'test'
});

connection.connect();
//查询
connection.query('select * from `mytable`', function(err, rows, fields) {
		if (err) throw err;
		console.log('查询结果为: ', rows);
});
//关闭连接
connection.end();


运行node



确实是能查询的哟!我突然相信真爱了。。。

更多mysql例子:

https://www.npmjs.com/package/mysql

posted @ 2015-11-03 11:21 tinyphp

Link: http://www.asm32.net/article_details.aspx?id=7101


浏览次数 0 发布时间 2016-10-27 10:10:33 从属分类 node.js 【评论】【 】【打印】【关闭
 
| www.asm32.net | 2006版 | 资料中心 | linux | asm/asm32 | C/C++ | VC++ | java | Python | 书签 | ASP.Net书签 | 京ICP备09029108号-1