使用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'
答案 0 :(得分: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();
答案 1 :(得分: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();
答案 2 :(得分:0)
在此模块的最新版本中,与mySQL建立的连接不是由
建立的mysql.createClient({});
但是
mysql.createConnection({});