sql node code example
Example 1: mssql query node js
const sql = require('mssql')
const query=`select * from table`;
config = {
database: "dbname",
options: {
enableArithAbort: true,
encrypt: true,
rowCollectionOnRequestCompletion: false,
},
parseJSON: true,
password: "password",
port: port,
server: "server ip or name",
user: "usenme",
};
sql.on('error', err => {
})
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
const mysql = require('mysql2');
const connection = mysql.createPool({
host: "localhost",
user: "",
password: "",
database: ""
});
module.exports = connection;
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;
Example 3: js read mysql database
const config = {
"table" : "customers",
"limit" : "50",
"offset" : "0"
};
_POST_REQUEST("link-to-server/database.php", 'config=' + JSON.stringify(config), (response) => {
var data = JSON.parse(response);
});