Home  >  Article  >  Web Front-end  >  How to access SQL database with Node.js

How to access SQL database with Node.js

青灯夜游
青灯夜游forward
2021-02-07 18:29:543005browse

This article will introduce you to the method of Node.js accessing SQL server. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to everyone.

How to access SQL database with Node.js

Related recommendations: "nodejs Tutorial"

1. Preparation: Create a new project


Install mssql module

2. Create db.js, the code is as follows:

/*2018年6月08日17:02:15
作者:洪伟富
mssql模块简单封装
*/
var mssql  =  require(  'mssql');
var db  = {};
var config  = {
user:  'sa',
password:  '123456',
server:  '10.10.10.3',
database:  'Face',
port:  1433,
options: {
encrypt:  true  // Use this if you're on Windows Azure
},
pool: {
min:  0,
max:  10,
idleTimeoutMillis:  3000
}
};

//执行sql,返回数据.
db.  sql  =  function (  sql,  callBack) {
var connection  =  new  mssql.  ConnectionPool(config,  function (  err) {
if (err) {
console.  log(err);
return;
}
var ps  =  new  mssql.  PreparedStatement(connection);
ps.  prepare(sql,  function (  err) {
if (err) {
console.  log(err);
return;
}
ps.  execute(  '',  function (  err,  result) {
if (err) {
console.  log(err);
return;
}

ps.  unprepare(  function (  err) {
if (err) {
console.  log(err);
callback(err,  null);
return;
}
callBack(err, result);
});
});
});
});
};

module.  exports  = db;

3. Create test.js test file, require introduces db.js, and calls the db.sql method to operate the SQL server database.

var db  =  require(  './db');
db.  sql(  'select * from People',  function (  err,  result) {
if (err) {
console.  log(err);
return;
}
for (i  =  0; i  < result.recordset.length; i  ++) {
var data  = result.recordset[i].Image;
console.  log(  "********************************************************************");
console.  log(data);
}

});

4. Run the test.js file to view the results


For more programming-related knowledge, please visit: ProgrammingTeaching! !

The above is the detailed content of How to access SQL database with Node.js. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:csdn.net. If there is any infringement, please contact admin@php.cn delete