1 install node-mysql
-
[lee@bogon node]$ npm install mysql
-
npm http GET
-
npm http 304
-
npm http GET
-
npm http GET
-
npm http 304
-
npm http 304
-
mysql@2.0.0-alpha8 node_modules/mysql
-
├── require-all@0.0.3
-
└── bignumber.js@1.0.1
2 create js file
[lee@bogon node]$ vi mysql_test.js
-
var mysql = require('mysql');
-
var TEST_DATABASE = 'db_test';
-
var TEST_TABLE = 'table_test1';
-
-
var connection = mysql.createConnection({
-
host : 'localhost',
-
user : 'root',
-
password : 'root',
-
});
-
-
connection.query('CREATE DATABASE '+TEST_DATABASE, function(err) {
-
if (err && err.number != mysql.ERROR_DB_CREATE_EXISTS) {
-
throw err;
-
}
-
});
-
-
connection.query('USE '+TEST_DATABASE);
-
-
connection.query(
-
' DROP TABLE '+'IF EXISTS '+TEST_TABLE
-
);
-
-
connection.query(
-
'CREATE TABLE '+TEST_TABLE+
-
'(id INT(11) AUTO_INCREMENT, '+
-
'name VARCHAR(255), '+
-
'PRIMARY KEY (id))'
-
);
-
-
connection.query(
-
'INSERT INTO '+TEST_TABLE+' '+
-
'SET name = ?',
-
['lee']
-
);
-
-
var query = connection.query(
-
'INSERT INTO '+TEST_TABLE+' '+
-
'SET name = ?',
-
['sophia']
-
);
-
-
connection.query(
-
'SELECT id,name FROM '+TEST_TABLE,
-
function selectCb(err, results, fields)
-
{
-
if (err) { throw err; }
-
for(var i = 0;i < results.length; ++i)
-
{
-
var data = 'id: ' + results[i]['id'] + ' name:' + results[i]['name'];
-
console.log(data);
-
}
-
console.log(results);
-
console.log(fields);
-
connection.end();
-
}
-
);
3 run
[lee@bogon node]$ node mysql_test.js
4 output
-
id: 1 name:lee
-
id: 2 name:sophia
-
[ { id: 1, name: 'lee' }, { id: 2, name: 'sophia' } ]
-
[ { catalog: 'def',
-
db: 'db_test',
-
table: 'table_test1',
-
orgTable: 'table_test1',
-
name: 'id',
-
orgName: 'id',
-
filler1: ,
-
charsetNr: 63,
-
length: undefined,
-
type: 3,
-
flags: 16899,
-
decimals: 0,
-
filler2: ,
-
default: undefined,
-
zeroFill: false,
-
protocol41: true,
-
fieldLength: 11 },
-
{ catalog: 'def',
-
db: 'db_test',
-
table: 'table_test1',
-
orgTable: 'table_test1',
-
name: 'name',
-
orgName: 'name',
-
filler1: ,
-
charsetNr: 33,
-
length: undefined,
-
type: 253,
-
flags: 0,
-
decimals: 0,
-
filler2: ,
-
default: undefined,
-
zeroFill: false,
-
protocol41: true,
-
fieldLength: 765 } ]
阅读(690) | 评论(0) | 转发(0) |