[nodejs] MySQL 커넥션 접속 후 데이터 가져오는 샘플
절차적으로 실행 되도록 테스트 되어진 nodejs용 MySql 커넥션 후 데이터 가져오는 샘플 입니다.
다른 언어를 사용해 봤다면 몇가지 문법적인 것만 익히면 어렵지 않습니다.
코드를 간결하게 하는 부분은 좀 사용을 해야 가능 할듯 합니다.
/*
* sleep.sleep(n): sleep for n seconds
* sleep.msleep(n): sleep for n miliseconds
* sleep.usleep(n): sleep for n microseconds (1 second is 1000000 microseconds)
*/
var fs = require('fs');
var sleep = require('sleep');
const mysql = require('mysql2/promise'); // get the client
const bluebird = require('bluebird'); // get the promise implementation, we will use bluebird
(async () => {
// create the connection, specify bluebird as Promise
const mycon = await mysql.createConnection({host:"서버주소", user: '디비유저', password: "디비통과번호", port: "디비포트", dateStrings: 'date', Promise: bluebird});
//console.log(mycon);
// query database
//const [rows, fields] = await connection.execute('SELECT * FROM `table` WHERE `name` = ? AND `age` > ?', ['Morty', 14]);
const sql = "SELECT * FROM test.test_table WHERE test_date='0000-00-00 00:00:00' LIMIT 3";
const [rows, fields] = await mycon.execute(sql);
var aRs;
for( var i=0; i<rows.length; i++ )
{
aRs = rows[i];
console.log(aRs);
console.log('한개의 필드: ' + aRs.test_user);
console.log('----------------------');
}
await process.exit();
await console.log('end2 ...');
})();
PHP하고는 형태가 좀 다르지만 어렵지 않게 사용이 가능 합니다.
● 참고자료