개발 창고/NodeJS
[NodeJS] How to import MS-SQL and use Connection Pool
로이제로
2023. 11. 22. 22:00
반응형
1. module 추가
/> npm install mssql
mssql 모듈을 추가해 줍니다.
2. import
const sql = require('mssql');
여기에서는 CommonJS로 이야기할 예정이므로 require를 사용합니다.
3. config 설정
const config = {
server: 'MSSQL서버IP'
, port: 1433
, options: { encrypt:false, database: '데이터베이스명', connectTimeout:15000 }
, authentication:{
type:"default"
, options:{
userName:"계정아이디"
, password:"계정비밀번호"
}
}
};
4. Connection Pool 생성
const pool = new sql.ConnectionPool(config)
.connect()
.then(pool => {
console.log('Connected to MSSQL')
return pool
})
.catch(err => console.log('Database Connection Failed! Bad Config: ', err))
5. Query 실행
async function main() {
try{
const con = await pool;
await con.query("SELECT 1", (err, recordset) => {
if(err) console.log("query error :", err)
else console.log(JSON.stringify(recordset))
});
}catch(e){
console.log(e);
}
}
main();
위 내용은 connection 맺어진 mssql pool에서 아래의 Query를 실행한 것과 같습니다.
SELECT 1
그 결과 위처럼 MSSQL을 연결한 후 Query를 실행하여, 결과로 1을 배열에 담아 반환했음을 확인할 수 있습니다.
전체 테스트 소스
// npm install mssql
const sql = require('mssql');
const config = {
server: 'MSSQL서버IP'
, port: 1433
, options: { encrypt:false, database: '데이터베이스명', connectTimeout:15000 }
, authentication:{
type:"default"
, options:{
userName:"계정아이디"
, password:"계정비밀번호"
}
}
};
const pool = new sql.ConnectionPool(config)
.connect()
.then(pool => {
console.log('Connected to MSSQL')
return pool
})
.catch(err => console.log('Database Connection Failed! Bad Config: ', err))
async function main() {
try{
const con = await pool;
await con.query("SELECT 1", (err, recordset) => {
if(err) console.log("query error :", err)
else console.log(JSON.stringify(recordset))
});
}catch(e){
console.log(e);
}
}
main();
반응형