我正在尝试使用nodejs(express(。
插入我的SQL Server DB表中我尝试过的一切都无法正常工作。
在我的app.js中,我有以下执行正确并连接的下面,但是我在挣扎的位置,如何将数据插入我的db表中。
app.js
var Connection = require('tedious').Connection;
var Request = require('tedious').Request;
var TYPES = require('tedious').TYPES;
var async = require('async');
var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var mysql = require('mysql');
var sql = require('mssql');
var index = require('./routes/index');
var users = require('./routes/users');
var homepage = require('./routes/homepage');
var app = express();
////// DB CONF //////
var config = {
userName: 'xxxxxxxxxxxxxx',
password: 'xxxxxxx',
server: 'xxxxxxxxxxx',
options: {
database: 'xxxxxxxxxxx'
}
}
var connection = new Connection(config);
connection.on('connect', function(err) {
if (err) {
console.log(err);
} else {
console.log('Connected');
}
});
您已经包含了MySQL库。现在,您必须创建MySQL连接。喜欢:
const writeDB = mysql.createConnection({
host: 'localhost',
user: 'root',
password: '********',
database: 'dbName'
});
创建连接运行查询之后:
let squerySet = "INSERT INTO weekDays (`id`, `date`, `day`) values ('1','2018-03-03', 'Monday');"
writeDB.query(squerySet,(err, result) => {
if(err){
return reject(err)
}
else {
resolve("carrierbillreceipt Table COPY DONE .....")
}
})
因为 writeDB.query
将返回承诺,然后您必须通过在承诺中创建它来处理这一点。喜欢:
const insertDays = () => {
return new Promise((resolve, reject) => {
let squerySet = "INSERT INTO weekDays (`id`, `date`, `day`) values ('1','2018-03-03', 'Monday');"
writeDB.query(squerySet,(err, result) => {
if(err){
return reject(err)
}
else {
resolve("insertDays Insert DONE .....")
}
})
})
}
您也可以插入一个JSON对象。喜欢:
let data = { "id": '1', "date":'2018-03-03', "day": 'Monday'}
writeDB.query(`INSERT INTO weekDays SET ?;`,[data],(err, result) => {
if(err){
return reject(err)
}
else {
resolve("insertDays Insert DONE .....")
}
})