Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
947 views
in Technique[技术] by (71.8m points)

node.js - Insert multiple columns and rows into SQL Server with node js

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...