0

使用 Packt 的Node Cookbook中的 mysql 模块和代码示例。

var mysql = require('mysql');
var client = mysql.createClient({
user: 'root',
password: 'sqlpassword',
//debug: true  
});

var ignore = [mysql.ERROR_DB_CREATE_EXISTS,
          mysql.ERROR_TABLE_EXISTS_ERROR];

client.on('error', function (err) {
if (ignore.indexOf(err.number) + 1) { return; }
throw err;
});

client.query('CREATE DATABASE quotes');
client.useDatabase('nodb');
client.query('CREATE TABLE quotes.quotes (' +
         'id INT NOT NULL AUTO_INCREMENT,' +
         'author VARCHAR( 128 ) NOT NULL,' +
         'quote TEXT NOT NULL, PRIMARY KEY (  id )' +
         ')');

client.query('INSERT INTO  quotes.quotes (' +
          'author, quote) ' +
          'VALUES ("Proof by analogy is fraud.", "Bjarne Stroustrup");');

client.end();

并且该代码返回我错误对象#没有方法'useDatabase'

4

3 回答 3

3

我相信您想在连接时指定数据库。

var mysql = require('mysql');
var client = mysql.createClient({
user: 'root',
password: 'sqlpassword',
database: 'nodb'
//debug: true  
});

var ignore = [mysql.ERROR_DB_CREATE_EXISTS,
          mysql.ERROR_TABLE_EXISTS_ERROR];

client.on('error', function (err) {
if (ignore.indexOf(err.number) + 1) { return; }
throw err;
});

client.query('CREATE DATABASE quotes');
client.query('CREATE TABLE quotes.quotes (' +
         'id INT NOT NULL AUTO_INCREMENT,' +
         'author VARCHAR( 128 ) NOT NULL,' +
         'quote TEXT NOT NULL, PRIMARY KEY (  id )' +
         ')');

client.query('INSERT INTO  quotes.quotes (' +
          'author, quote) ' +
          'VALUES ("Proof by analogy is fraud.", "Bjarne Stroustrup");');

client.end();
于 2013-02-17T03:50:32.590 回答
1

将 node-mysql v0.9 示例迁移到 v2.0。https://github.com/felixge/node-mysql

var mysql = require('mysql');

var client = mysql.createConnection({
  host: 'localhost',
  user: 'root',
  password: 'OURPASSWORD'
  //debug: true
});

var ignore = [mysql.ERROR_DB_CREATE_EXISTS,
              mysql.ERROR_TABLE_EXISTS_ERROR];

client.on('error', function (err) {
  if (ignore.indexOf(err.number) + 1) { return; }
  throw err;
});

client.query('CREATE DATABASE quotes');
client.query('USE quotes');

client.query('CREATE TABLE quotes.quotes (' +
             'id INT NOT NULL AUTO_INCREMENT,' +
             'author VARCHAR( 128 ) NOT NULL,' +
             'quote TEXT NOT NULL, PRIMARY KEY (  id )' +
             ')');

client.query('INSERT INTO  quotes.quotes (' +
              'author, quote) ' +
              'VALUES ("Bjarne Stroustrup", "Proof by analogy is fraud.");');

client.end();
于 2013-06-30T07:39:18.840 回答
0

在此模块的最新版本中,与 mySQL 的连接不是由

mysql.createClient({});

但与

mysql.createConnection({});
于 2013-02-17T13:53:20.333 回答