node.js连接 mysql

本文演示了如何使用Node.js连接MySQL数据库并执行基本操作,包括创建数据库、表格、插入记录及查询。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

npm install mysql

var client = require('mysql').createClient({'host':'localhost','port':3306,'user':'root','password':'root'});
TEST_DATABASE = 'nodejs_mysql_test',
TEST_TABLE = 'test';

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();
}

);

结果:

[ { id: 1,
title: 'super cool',
text: 'this is a nice text',
created: Mon, 16 Aug 2010 02:00:23 GMT },
{ id: 2,
title: 'another entry',
text: 'because 2 entries make a better test',
created: Mon, 16 Aug 2010 04:42:15 GMT } ]
{ id:
{ length: 51,
received: 51,
number: 2,
type: 4,
catalog: 'def',
db: 'nodejs_mysql_test',
table: 'test',
originalTable: 'test',
name: 'id',
originalName: 'id',
charsetNumber: 63,
fieldLength: 11,
fieldType: 3,
flags: 16899,
decimals: 0 },
title:
{ length: 57,
received: 57,
number: 3,
type: 4,
catalog: 'def',
db: 'nodejs_mysql_test',
table: 'test',
originalTable: 'test',
name: 'title',
originalName: 'title',
charsetNumber: 192,
fieldLength: 765,
fieldType: 253,
flags: 0,
decimals: 0 },
text:
{ length: 55,
received: 55,
number: 4,
type: 4,
catalog: 'def',
db: 'nodejs_mysql_test',
table: 'test',
originalTable: 'test',
name: 'text',
originalName: 'text',
charsetNumber: 192,
fieldLength: 196605,
fieldType: 252,
flags: 16,
decimals: 0 },
created:
{ length: 61,
received: 61,
number: 5,
type: 4,
catalog: 'def',
db: 'nodejs_mysql_test',
table: 'test',
originalTable: 'test',
name: 'created',
originalName: 'created',
charsetNumber: 63,
fieldLength: 19,
fieldType: 12,
flags: 128,
decimals: 0 } }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值