mysql 모듈
데이터베이스와 서버 인스턴스를 연결하기 위한 mysql 모듈
npm install mysql
const mysql = require('mysql');
const con = mysql.createConnecion(
// code, code, code
);
con.connect(function(err){
if(err){
// code
}
console.log('successfulconnected')
}
con.query('query문', function(err,result, fields){
if(err) throw error;
console.log('successfulconnected')
}
con.query('SELECT * FROM users', function(err){
if(err) throw error;
console.log('successfulconnected')
}
con.query('SELECT * FROM users WHERE name = ?',
['kimcoding'], // ? 자리에 들어간다.
function(err){
if(err) throw error;
console.log('successfulconnected')
}
connection.query('UPDATE users SET foo = ?, bar = ?, baz = ? WHERE id = ?',
['a', 'b', 'c', userId],
function (error, results, fields) {
if (error) throw error;
// ...
});
var userId = 1;
var columns = ['username', 'email'];
var query = con.query('SELECT ?? FROM ?? WHERE id = ?',
[columns, 'users', userId],
function (error, results, fields) {
if (error) throw error;
// ...
});
console.log(query.sql); // SELECT `username`, `email` FROM `users` WHERE id = 1
con.query('INSERT INTO posts SET ?',
{title: 'test'},
function (error, results, fields) {
if (error) throw error;
console.log(results.insertId);
});
con.query('DELETE FROM posts WHERE title = "wrong"',
function (error, results, fields) {
if (error) throw error;
console.log('deleted ' + results.affectedRows + ' rows');
})
con.query('UPDATE posts SET ...',
function (error, results, fields) {
if (error) throw error;
console.log('changed ' + results.changedRows + ' rows');
})
var sql = "INSERT INTO customers (name, address) VALUES ?";
var params = [
["John", "Highway 71"],
["Peter", "Lowstreet 4"],
["Amy", "Apple st 652"],
["Hannah", "Mountain 21"],
["Michael", "Valley 345"],
["Sandy", "Ocean blvd 2"],
["Betty", "Green Grass 1"],
["Richard", "Sky st 331"],
["Susan", "One way 98"],
["Vicky", "Yellow Garden 2"],
["Ben", "Park Lane 38"],
];
con.query(sql, [params], function (err, result) {
if (err) throw err;
console.log("Number of records inserted: " + result.affectedRows);
});