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

How to access SQL database with Node.js

青灯夜游
Release: 2021-02-07 18:29:54
forward
3031 people have browsed it

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;
Copy after login

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);
}

});
Copy after login

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!

Related labels:
source:csdn.net
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template