「Node.js」MySQLからselect文によりテーブルのデータを取得サンプル
構文
conn.query(sql,function (err, result) { some code}
使用例
var mysql = require('mysql');
var conn= mysql.createConnection({
host : 'localhost',//接続先ホスト
user : 'root',//ユーザー名
password : '123456', //パスワード
port: '3306', //ポート番号
database : 'arkgamedb' //DB名
});
conn.connect();
var sql = 'select * from usertable';
//クエリ作成
conn.query(sql,function (err, result) {
if(err){
console.log('[select ERROR] - ',err.message);
return;
}
console.log('--------------------------select----------------------------');
console.log(result);
console.log('------------------------------------------------------------\n\n');
});
conn.end();
var mysql = require('mysql');
var conn= mysql.createConnection({
host : 'localhost',//接続先ホスト
user : 'root',//ユーザー名
password : '123456', //パスワード
port: '3306', //ポート番号
database : 'arkgamedb' //DB名
});
conn.connect();
var sql = 'select * from usertable';
//クエリ作成
conn.query(sql,function (err, result) {
if(err){
console.log('[select ERROR] - ',err.message);
return;
}
console.log('--------------------------select----------------------------');
console.log(result);
console.log('------------------------------------------------------------\n\n');
});
conn.end();
var mysql = require('mysql'); var conn= mysql.createConnection({ host : 'localhost',//接続先ホスト user : 'root',//ユーザー名 password : '123456', //パスワード port: '3306', //ポート番号 database : 'arkgamedb' //DB名 }); conn.connect(); var sql = 'select * from usertable'; //クエリ作成 conn.query(sql,function (err, result) { if(err){ console.log('[select ERROR] - ',err.message); return; } console.log('--------------------------select----------------------------'); console.log(result); console.log('------------------------------------------------------------\n\n'); }); conn.end();
実行結果
$ node sample.js
--------------------------SELECT----------------------------
[ RowDataPacket {
userid: 101,
name: 'user001',
age: '21',
email: '11@example.com' },
RowDataPacket {
userid: 102,
name: 'user002',
age: '32',
email: '12@example.com' },
RowDataPacket {
userid: 103,
name: 'user003',
age: '33',
email: '13@example.com' } ]
------------------------------------------------------------
--------------------------SELECT----------------------------
[ RowDataPacket {
userid: 101,
name: 'user001',
age: '21',
email: '11@example.com' },
RowDataPacket {
userid: 102,
name: 'user002',
age: '32',
email: '12@example.com' },
RowDataPacket {
userid: 103,
name: 'user003',
age: '33',
email: '13@example.com' } ]
------------------------------------------------------------
--------------------------SELECT---------------------------- [ RowDataPacket { userid: 101, name: 'user001', age: '21', email: '11@example.com' }, RowDataPacket { userid: 102, name: 'user002', age: '32', email: '12@example.com' }, RowDataPacket { userid: 103, name: 'user003', age: '33', email: '13@example.com' } ] ------------------------------------------------------------