您好,欢迎来到三六零分类信息网!老站,搜索引擎当天收录,欢迎发信息

nodejs中操作mysql数据库示例_node.js

2025/10/18 10:42:09发布20次查看
引言: 继前面的nodejs的hello,world!我们还可以看到其他强大之处,nodejs现在社区的火热,以及大批工程师对它的支持之下,现在已经陆续的引出了大量的module出来了。
内容: 下面这个所演示的是nodejs与mysql 的交互。
这时需要为nodejs加入mysql 的module了,这时前一章说到的npm(node package manager)启到作用了。
把mysql module装到nodejs中:
复制代码 代码如下:
$npm install mysql
js脚本 mysqltest.js
复制代码 代码如下:
// mysqltest.js
//加载mysql module
var client = require(‘mysql').client,
client = new client(),//要创建的数据库名
test_database = ‘nodejs_mysql_test',
//要创建的表名
test_table = ‘test';
//用户名
client.user = ‘root';
//密码
client.password = ‘root';
//创建连接
client.connect();
client.query(‘create database ‘+test_database, function(err) {
if (err && err.number != client.error_db_create_exists) {
throw err;
}
});
// if no callback is provided, any errors will be emitted as `'error'`
// events by the client
client.query(‘use ‘+test_database);
client.query(
‘create table ‘+test_table+
‘(id int(11) auto_increment, ‘+
‘title varchar(255), ‘+
‘text text, ‘+
‘created datetime, ‘+
‘primary key (id))'
);
client.query(
‘insert into ‘+test_table+' ‘+
‘set title = ?, text = ?, created = ?',
['super cool', 'this is a nice text', '2010-08-16 10:00:23']
);
var query = client.query(
‘insert into ‘+test_table+' ‘+
‘set title = ?, text = ?, created = ?',
['another entry', 'because 2 entries make a better test', '2010-08-16 12:42:15']
);
client.query(
‘select * from ‘+test_table,
function selectcb(err, results, fields) {
if (err) {
throw err;
}
console.log(results);
console.log(fields);
client.end();
}
);
执行脚本
复制代码 代码如下:
node mysqltest.js
效果如下:
该用户其它信息

VIP推荐

免费发布信息,免费发布B2B信息网站平台 - 三六零分类信息网 沪ICP备09012988号-2
企业名录 Product