2013-02-17 33 views
0

使用來自Packt的Node Cookbook的mysql模塊和代碼示例。Node.js 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」

+2

結帳的文檔https://github.com/felixge/node-mysql – zsong 2013-02-17 00:45:22

回答

3

我beleive你想連接時指定數據庫。

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(); 
+0

我不這麼認爲,因爲這個代碼 'client.query(' CREATE DATABASE引號 ');'創造新的基地。 – khex 2013-02-17 13:42:12

0

在該模塊連接到MySQL的最新版本由

mysql.createClient({}); 

mysql.createConnection({}); 
1

遷移節點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();