按照这篇操作mysql的指引,我远程操作了我另一台电脑的mysql数据库。
var mysql = require('mysql');
var connection = mysql.createConnection({
host : '10.58.187.217',//远程MySQL数据库的ip地址
user : 'root',
password : '',
}); //试试有米有连接上mysql
connection.connect(function(error, results) {
if(error) {
console.log('Connection Error: ' + error.message);
return;
}
console.log('Connected to MySQL');
ClientConnectionReady(connection);
}); //试试有米有连接上test数据库
ClientConnectionReady = function(connection)
{
connection.query('USE test', function(error, results) {
if(error) {
console.log('ClientConnectionReady Error: ' + error.message);
connection.end();
return;
}
console.log("connect test");
//ClientReady(connection);
GetData(connection);
});
}; //向test数据库中的goods表中插入数据
ClientReady = function(connection)
{
var values = [, 'mac'];
connection.query('INSERT INTO goods SET price = ?, goodName = ?', values,
function(error, results) {
if(error) {
console.log("ClientReady Error: " + error.message);
connection.end();
return;
}
console.log('Inserted: ' + results.affectedRows + ' row.');
console.log('Id inserted: ' + results.insertId);
}
);
GetData(connection);
} //展示test数据库中的goods表的所有数据
GetData = function(connection) {
connection.query(
'SELECT * FROM goods',
function selectCb(error, results, fields) {
if (error) {
console.log('GetData Error: ' + error.message);
connection.end();
return;
}
console.log("connect goods");
console.log(results);
if (results.length > ) {
var firstResult = results[results.length-];
//console.log('price: ' + firstResult['price']);
//console.log('goodName: ' + firstResult['goodName']);
}
})
}
结果是:
本文的sql2.js下载链接在此。