mongodb 와 상당히 흡사합니다. 공통적으로 들어가는 부분은 db 커넥션시의 유저네임과 비번이며 (예제에선 root / 123qwe 부분입니다.) 어느 데이터베이스를 쓰는지 명시를 해야 합니다.(예제에선 use test 부분입니다.)
전체 소스는
1. 먼저 테이블 생성
var mysql = require('mysql'); var client = mysql.createConnection({ user:'root', password:'123qwe'}); client.connect(); client.query('use test'); client.query('create table local (area varchar(100) character set utf8, idx int) default charset = utf8',function(error, rows, fields){ if(error) throw error; else{ console.log(rows); } }); client.end();
2. insert .
var mysql = require('mysql'); var client = mysql.createConnection({ user:'root', password:'123qwe'}); client.connect(); client.query('use test'); var data = ['서울특별시 종로구',1]; client.query('insert into local values(?,?)',data, function(error, result){ if(!error){ console.log(result); } }); client.end();
3. select
var mysql = require('mysql'); var client = mysql.createConnection({ user:'root', password:'123qwe'}); client.connect(); client.query('use test'); client.query('select area, idx from local', function(error, rows, fields){ if(error) throw error; else{ console.log(rows); } }); client.end();
4. update
var mysql = require('mysql'); var client = mysql.createConnection({ user:'root', password:'123qwe'}); client.connect(); client.query('use test'); var data = ['서울특별시 중구', 1]; client.query('update local set area = ? where idx=?',data,function(error, rows){ if(error) throw error; else{ console.log(rows); } }); client.end();
5. count
var mysql = require('mysql'); var client = mysql.createConnection({ user:'root', password:'123qwe'}); client.connect(); client.query('use test'); client.query('select count(idx) as count from local',function(error, rows, fields){ if(error) throw error; else{ console.log(rows); } }); client.end();
6. delete
var mysql = require('mysql'); var client = mysql.createConnection({ user:'root', password:'123qwe'}); client.connect(); client.query('use test'); var data = [1]; client.query('delete from local where idx=?',data,function(error, rows){ if(error) throw error; else{ console.log(rows); } }); client.end();
'Node.js > 9. mysql' 카테고리의 다른 글
mysql insert 한 데이터의 한글이 깨진다면 (0) | 2014.05.01 |
---|---|
9-1 ubuntu mysql 설치 (0) | 2014.04.15 |