nodejs 连接mysql

本文介绍如何在Ubuntu 10.04系统中安装Node.js的MySQL模块,并通过示例代码展示如何使用该模块连接MySQL数据库并进行基本操作。

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

运行环境:
1、运行平台:ubuntu 10.04
2、nodejs版本:v0.10.5

操作过程如下:

leekwen@ubuntu:~$ sudo -s
[sudo] password for leekwen: 
root@ubuntu:~# cat /etc/issue
Ubuntu 10.04.4 LTS \n \l
root@ubuntu:~# uname -a
Linux ubuntu 2.6.32-38-generic #83-Ubuntu SMP Wed Jan 4 11:13:04 UTC 2012 i686 GNU/Linux
root@ubuntu:~# node -v
v0.10.5
root@ubuntu:~# npm -v
1.2.18
root@ubuntu:~# which node
/usr/local/bin/node
root@ubuntu:~# which npm
/usr/local/bin/npm
root@ubuntu:~# cd /usr/local/lib/node_modules/
root@ubuntu:/usr/local/lib/node_modules# ls -l
total 4
drwxr-xr-x 9 root root 4096 2013-05-21 18:09 npm
root@ubuntu:/usr/local/lib/node_modules# cd npm/
root@ubuntu:/usr/local/lib/node_modules/npm# ls
AUTHORS  cli.js     doc   lib      Makefile  node_modules  README.md
bin      configure  html  LICENSE  man       package.json  scripts
root@ubuntu:/usr/local/lib/node_modules/npm# cd node_modules/
root@ubuntu:/usr/local/lib/node_modules/npm/node_modules# ls
abbrev        graceful-fs        nopt                 request
ansi          inherits           npmconf              retry
archy         ini                npmlog               rimraf
block-stream  init-package-json  npm-registry-client  semver
chmodr        lockfile           once                 slide
chownr        lru-cache          opener               tar
cmd-shim      minimatch          osenv                uid-number
fstream       mkdirp             read                 which
fstream-npm   mysql              read-installed
glob          node-gyp           read-package-json
root@ubuntu:/usr/local/lib/node_modules/npm/node_modules# pwd
/usr/local/lib/node_modules/npm/node_modules
root@ubuntu:/usr/local/lib/node_modules/npm/node_modules# npm install mysql
npm http GET https://registry.npmjs.org/require-all/0.0.3
npm http GET https://registry.npmjs.org/bignumber.js/1.0.1
npm http 304 https://registry.npmjs.org/require-all/0.0.3
npm http 304 https://registry.npmjs.org/bignumber.js/1.0.1
mysql@2.0.0-alpha8 mysql
├── require-all@0.0.3
└── bignumber.js@1.0.1

到此已经完成了,nodejs所需要的mysql模块的安装!
下面写上一段代码,用来连接mysql,并操作数据库:

root@ubuntu:~# vi mysql_test.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 = 'leekwen';
//创建连接
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();
  }
);

运行上述代码,结果如下:

root@ubuntu:~# node mysql_test.js 
[ { id: 1,
    title: 'super cool',
    text: 'this is a nice text',
    created: Mon Aug 16 2010 10:00:23 GMT+0800 (CST) },
  { id: 2,
    title: 'another entry',
    text: 'because 2 entries make a better test',
    created: Mon Aug 16 2010 12:42:15 GMT+0800 (CST) } ]
[ { catalog: 'def',
    db: 'nodejs_mysql_test',
    table: 'test',
    orgTable: 'test',
    name: 'id',
    orgName: 'id',
    filler1: <Buffer 0c>,
    charsetNr: 63,
    length: undefined,
    type: 3,
    flags: 16899,
    decimals: 0,
    filler2: <Buffer 00 00>,
    default: undefined,
    zeroFill: false,
    protocol41: true,
    fieldLength: 11 },
  { catalog: 'def',
    db: 'nodejs_mysql_test',
    table: 'test',
    orgTable: 'test',
    name: 'title',
    orgName: 'title',
    filler1: <Buffer 0c>,
    charsetNr: 33,
    length: undefined,
    type: 253,
    flags: 0,
    decimals: 0,
    filler2: <Buffer 00 00>,
    default: undefined,
    zeroFill: false,
    protocol41: true,
    fieldLength: 765 },
  { catalog: 'def',
    db: 'nodejs_mysql_test',
    table: 'test',
    orgTable: 'test',
    name: 'text',
    orgName: 'text',
    filler1: <Buffer 0c>,
    charsetNr: 33,
    length: undefined,
    type: 252,
    flags: 16,
    decimals: 0,
    filler2: <Buffer 00 00>,
    default: undefined,
    zeroFill: false,
    protocol41: true,
    fieldLength: 196605 },
  { catalog: 'def',
    db: 'nodejs_mysql_test',
    table: 'test',
    orgTable: 'test',
    name: 'created',
    orgName: 'created',
    filler1: <Buffer 0c>,
    charsetNr: 63,
    length: undefined,
    type: 12,
    flags: 128,
    decimals: 0,
    filler2: <Buffer 00 00>,
    default: undefined,
    zeroFill: false,
    protocol41: true,
    fieldLength: 19 } ]

root@ubuntu:~# clear
查看数据库,看是否操作成功?!

root@ubuntu:~# mysql -uroot -pleekwen
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 40
Server version: 5.1.62-0ubuntu0.10.04.1 (Ubuntu)

Copyright (c) 2000, 2011, Oracle and/or its affiliates. All rights reserved.

Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

mysql> show databases;
+--------------------+
| Database           |
+--------------------+
| information_schema |
| mysql              |
| nodejs_mysql_test  |
+--------------------+
3 rows in set (0.00 sec)

mysql> use nodejs_mysql_test;
Reading table information for completion of table and column names
You can turn off this feature to get a quicker startup with -A

Database changed
mysql> show tables;
+-----------------------------+
| Tables_in_nodejs_mysql_test |
+-----------------------------+
| test                        |
+-----------------------------+
1 row in set (0.00 sec)

mysql> select * from test;
+----+---------------+--------------------------------------+---------------------+
| id | title         | text                                 | created             |
+----+---------------+--------------------------------------+---------------------+
|  1 | super cool    | this is a nice text                  | 2010-08-16 10:00:23 |
|  2 | another entry | because 2 entries make a better test | 2010-08-16 12:42:15 |
+----+---------------+--------------------------------------+---------------------+
2 rows in set (0.00 sec)

mysql> quit;
Bye
查看后得知数据库中有数据,说明JS代码已经成功运行,并对mysql数据库进行了操作!
以上代码参考如下链接:http://www.iteye.com/topic/968847 
但因版本问题,适当地做了修改,才使运行可以成功!!



                
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Leekwen

您的鼓励,是我坚持更新的动力!

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值