问题
I'm trying to to make a script that reads from a nosql and inserts into a SQL Server database.
That said I'm reading collections dynamically, so I need something to do things like
var columns = [ 1, 2, 3, 4 ...]
var values = [a, b, c ,4 ...]
request.query("INSERT INTO TABLE (" + [columns] + ") VALUES ( " [values] ");"
I have some collections with up to like 27 columns and I can't hog the database by inserting each value as I have like 20.000.000 registers to do... can't find anything that can do that inside a transaction, so I would appreciate any suggestions
回答1:
first download sql server from npm
npm install mssql
then try like this:
var sql = require("mssql");
// config for your database
var config = {
user: 'sa',
password: 'mypassword',
server: 'localhost',
database: 'SchoolDB'
};
// connect to your database
sql.connect(config, function (err) {
if (err) throw err;
console.log("Connected!");
var sql = "INSERT INTO customers (name, address) VALUES ?";
var values = [
['John', 'Highway 71'],
['Peter', 'Lowstreet 4'],
['Amy', 'Apple st 652'],
['Hannah', 'Mountain 21'],
['Michael', 'Valley 345'],
['Sandy', 'Ocean blvd 2'],
['Betty', 'Green Grass 1'],
['Richard', 'Sky st 331'],
['Susan', 'One way 98'],
['Vicky', 'Yellow Garden 2'],
['Ben', 'Park Lane 38'],
['William', 'Central st 954'],
['Chuck', 'Main Road 989'],
['Viola', 'Sideway 1633']
];
con.query(sql, [values], function (err, result) {
if (err) throw err;
console.log("Number of records inserted: " + result.affectedRows); }); });
回答2:
var columns = [ 1, 2, 3, 4 ...]
var values = [a, b, c ,4 ...]
request.query(`INSERT INTO TABLE (${columns}) VALUES ?`), [[values]])
columns is an array so will have convert into a string for removing '[' and ']' brackets.
来源:https://stackoverflow.com/questions/50840196/insert-multiple-columns-and-rows-into-sql-server-with-node-js