how to use sql in database in node js code example
Example 1: mssql query node js
const sql = require('mssql')
const query=`select * from table`;
config = {
database: "dbname",
// can keep these option required with latest version of mssql npm package
options: {
enableArithAbort: true,
encrypt: true,
rowCollectionOnRequestCompletion: false,
},
parseJSON: true,
password: "password",
port: port, // if youe database running on difrent port then 1433
server: "server ip or name",
user: "usenme",
};
sql.on('error', err => {
// ... error handler
})
sql.connect(config).then(pool => {
return pool.request()
.query(query)
}).then(result => {
console.log(result.recordset)
}).catch(err => {
console.log(err)
});
Example 2: how to manage a db connection in javascript
//put these lines in a seperate file
const mysql = require('mysql2');
const connection = mysql.createPool({
host: "localhost",
user: "",
password: "",
database: ""
// here you can set connection limits and so on
});
module.exports = connection;
//put these on destination page
const connection = require('../util/connection');
async function getAll() {
const sql = "SELECT * FROM tableName";
const [rows] = await connection.promise().query(sql);
return rows;
}
exports.getAll = getAll;