sitelink1 | https://blog.naver.com/n_jihyeon/221806066778 |
---|---|
sitelink2 | https://www.npmjs.com/package/mysql2 |
sitelink3 | |
extra_vars4 | |
extra_vars5 | |
extra_vars6 |
mysql 모듈 예제
/** * History
* author date content
* ===============================================
* OOO 19-03-23 유일키 조회 API 최초 생성
* OOO 19-05-19 유일키 선택 후 사용여부 Y로 변경
* ===============================================
* @params token
* @기능 유일키 조회 및 상태 변경
*/
saleApi.get("/api/buyMemo", tokenHandler.verifyToken, (req, res) => {
// 토큰 유효성 검사
const token = req.query.token;
req.tokenContent = tokenHandler.verifyData(token);
// token error
if (req.tokenContent.errCode != errCode.OK) {
res.status(errCode.OK);
res.json(req.tokenContent);
return;
}
const pool = carrotCommon.getConnectionPool();
pool.getConnection((err, connection) => {
// DB connection error
if (err) {
res.status(errCode.Ok);
res.json(errorHandler.ConnectionErrorHandler(err, connection));
return;
}
connection.beginTransaction(err => { /* transaction 에러 처리 */ if (err) {
res.status(errCode.OK);
res.json(errorHandler.TransactionErrorHandler(err, connection));
return;
}
const query1 = " SELECT UNIQ_KEY as uniqKey " + " , UNIQ_KEY_ID as uniqKeyId " + " FROM DEPOSIT_UNIQUE_KEY " + " WHERE IS_USED = 'N' " + " LIMIT 1 ";
connection.query(query1, (err, rows) => {
// SQL error
if (err) {
res.status(errCode.OK);
res.json(errorHandler.QueryErrorHandler(err, connection));
return;
}
if (rows.length == 0) {
res.status(errCode.OK);
res.json({
errCode: errCode.NOTFOUND,
msg: "사용 가능한 입금키가 없습니다."
});
return;
}
let uniqueKey = rows[0].uniqKey;
let uniqueKeyId = rows[0].uniqKeyId;
const query2 = " UPDATE DEPOSIT_UNIQUE_KEY " + " SET IS_USED = 'Y' " + " WHERE UNIQ_KEY_ID = ? ";
connection.query(query2, uniqueKeyId, (err, result) => {
// SQL error
if (err) {
// 실패시 rollback
connection.rollback(err => {
// Rollback error
if (err) {
res.status(errCode.OK);
res.json(errorHandler.TransactionErrorHandler(err, connection));
return;
}
res.status(errCode.OK);
res.json({
errCode: errCode.OK,
msg: "ROLLBACK 완료"
});
return;
});
res.status(errCode.OK);
res.json(errorHandler.QueryErrorHandler(err, connection));
return;
}
if (result.affectedRows > 0) {
connection.commit(err => {
if (err) {
res.status(errCode.OK);
res.json(errorHandler.TransactionErrorHandler(err, connection));
connection.rollback(err => {
res.status(errCode.OK);
res.json(errorHandler.TransactionErrorHandler(err, connection));
return;
});
}
});
res.status(errCode.OK);
res.json({
errCode: errCode.OK,
uniqueKey: uniqueKey,
uniqueKeyId: uniqueKeyId
});
return;
} else {
res.status(errCode.OK);
res.json({
errCode: errCode.UPDATEERROR,
msg: "입금키 업데이트에 실패하였습니다."
});
return;
}
});
});
});
connection.release();
});
});
mysql2 모듈 예제
// uploadStrategy 는 file 처리를 위한 multer 모듈 사용으로 추가된 코드입니다!
router.post("/api/restaurant", uploadStrategy, asyncHandler(async(req, res, next) => {
let file = req.file;
if (!file) {
res.status(errCode.OK).json({
errCode: errCode.BADREQUEST,
msg: "file이 없습니다."
});
return;
} /* file 처리 로직 생략 */
const params = req.body.params;
/* input 검증 */
if (...) {
// ...
return;
}
const connection = await pool.getConnection();
await connection.beginTransaction();
let resId try {
const queryString01 = " SELECT UUID() as uuid";
let result = await connection.query(queryString01);
if (result[0].length < 1) {
throw new Error('uuid was not created');
}
resId = result[0][0].uuid
// 'result[0][0]' looks like wired, but this library returns a tuple when the result of query is a one records.
// So if we want just the first record of the result, we can access it with result[0][0].
const queryString02 = `INSERT INTO RESTAURANT ( ... ) VALUES ( ... )`;
let qureyParam02 = [...]const result02 = await connection.execute(queryString02, qureyParam02)if (result02[0].affectedRows == 0) {
throw new Error('affectedRows is zero where restaurant table')
}
if (result02[0].affectedRows == 1) {
console.log('successfully inserted into restaurant');
}
const queryString03 = `INSERT INTO MENU ( ... ) VALUES ( ... )`;
const result03 = await connection.execute(queryString03, [resId])if (result03[0].affectedRows == 0) {
throw new Error('affectedRows is zero where menu table')
}
if (result03[0].affectedRows == 1) {
console.log('successfully inserted into menu');
}
await connection.commit();
res.status(errCode.OK).json({
errCode: errCode.OK,
msg: "글 등록 완료"
});
} catch (err) {
await connection.rollback();
res.status(errCode.OK)res.json({
errCode: errCode.SERVERERROR,
msg: "식당 정보 등록에 실패하였습니다."
});
throw err;
}
finally {
connection.release();
}
}));
mysql2 모듈 사용시 주의점
1. query 의 실행 결과의 데이터 타입에서 select문 실행으로 record 길이가 1인 결과를 return 하는 경우 데이터 타입을 tuple 로 return함
> const [rows, fields]로 선언후 row를 받던가, const result 로 선언 후 result[0][0] 로 rows 에 접근하면 됨
2. mysql2 에서는 pool.query() 함수로 select문만 실행 가능하며, 조회가 아닌 쿼리들은 pool.execute()로만 실행 가능 (select 문도 execute로 실행 가능)
댓글 0
번호 | 제목 | 글쓴이 | 날짜 | 조회 수 |
---|---|---|---|---|
13 | Node.js 에서 Bulk INSERT 를 하는 방법 (multi insert) | 황제낙엽 | 2021.02.02 | 969 |
» | mysql, mysql2 모듈 버전 비교 | 황제낙엽 | 2021.01.31 | 333 |
11 |
ORM 툴 Sequelize
![]() | 황제낙엽 | 2021.01.27 | 80 |
10 |
[connection과 pool-05] pool 생성이 너무 많은 경우의 database에서의 에러 - Too many connections
![]() | 황제낙엽 | 2021.01.27 | 127 |
9 | [connection과 pool-03] mysql.createPool 과 connection.query | 황제낙엽 | 2021.01.27 | 593 |
8 | [connection과 pool-02] mysql.createPool 과 pool.query | 황제낙엽 | 2021.01.27 | 113 |
7 | [connection과 pool-01] mysql.createConnection 과 connection.query | 황제낙엽 | 2021.01.27 | 107 |
6 | [T아카데미/Node.js 프로그래밍/MySQL] createPool, getConnection 의 간단한 예제 (강의 예제) | 황제낙엽 | 2021.01.27 | 106 |
5 | 여러 개의 데이터 베이스 연결을 동시에 관리하는 PoolCluster | 황제낙엽 | 2021.01.16 | 2374 |
4 | connetion pooling 과 connection leak | 황제낙엽 | 2021.01.16 | 96 |
3 | no pooling 상태에서 beginTransaction 콜백을 이용한 Transaction 처리 | 황제낙엽 | 2021.01.16 | 77 |
2 | mysql.escape()로 where 문 작성 | 황제낙엽 | 2021.01.16 | 100 |
1 | mysql basic (mysql 설치, 접속, 조회) | 황제낙엽 | 2021.01.12 | 165 |