一次将多行插入sqlite数据库

时间:2019-01-21 10:27:34

标签: node.js sqlite

我想使用一个插入语句将多行插入sqlite数据库。

在Node JS中,sqlite3库允许我们执行here所引用的操作。

但是在本教程中,只有一列,在插入具有多列的行时遇到了问题。

var csv = require('csv');
var fs = require('fs');
const sqlite3 = require('sqlite3').verbose();


// opening the database connection
let db = new sqlite3.Database('CSVtoDB_CSVParse//sample.db');

var parser = csv.parse({delimiter: ','}, function(err, data) {
    console.log(data);    
    languages = data;
    let placeholders = languages.map((language) => '(?,?)').join(',');
    let sql = 'INSERT INTO sample VALUES ' + placeholders;

    // output the INSERT statement
    console.log(sql);

    db.run(sql, languages, function(err) {
    if (err) {
        return console.error(err.message);
    }
    console.log(`Rows inserted ${this.changes}`);
    });

});

fs.createReadStream('CSVtoDB_CSVParse/sample1.csv').pipe(parser);

解析CSV后我在数据对象中得到的内容是这样的

[ [ 'id', 'name' ],
  [ '1', 'A' ],
  [ '2', 'B' ],
  [ '3', 'C' ],
  [ '4', 'D' ],
  [ '5', 'E' ],
  [ '6', 'F' ],
  [ '7', 'G' ],
  [ '8', 'H' ],
  [ '9', 'I' ],
  [ '10', 'J' ] ]

但是插入后,我的数据库表的数据显示如下,

sqlite> select * from sample;
|
|
|
|
|
|
|
|
|
|
|

输出:

  [ '1', 'A' ],
  [ '2', 'B' ],
  [ '3', 'C' ],
  [ '4', 'D' ],
  [ '5', 'E' ],
  [ '6', 'F' ],
  [ '7', 'G' ],
  [ '8', 'H' ],
  [ '9', 'I' ],
  [ '10', 'J' ] ]
INSERT INTO sample VALUES (?,?),(?,?),(?,?),(?,?),(?,?),(?,?),(?,?),(?,?),(?,?),(?,?),(?,?)
Rows inserted 11

有人遇到这样的问题吗? 预先感谢您的帮助。

1 个答案:

答案 0 :(得分:0)

使用Node js将用户名和密码插入SqliteDB

login.html

<form action="auth" method="POST">
<input type="text" name="username" placeholder="Username" autocomplete="off" required>
<input type="password" name="password" placeholder="Password" autocomplete="off" required>
<input type="submit">   
</form>

login.js

    const sqlite3 = require('sqlite3').verbose();//getting the Sqlite3 DB
    var express = require('express');//require the Express framework
    var session = require('express-session');
    var bodyParser = require('body-parser');
    var path = require('path');
    let db = new sqlite3.Database('./NodeTest.db');//getting the DataBase from Databasename
    var app = express();
    app.use(session({
        secret: 'secret',
        resave: true,
        saveUninitialized: true
    }));
    app.use(bodyParser.urlencoded({extended : true}));
    app.use(bodyParser.json());    
    app.get('/', function(request, response) {
        response.sendFile(path.join(__dirname + '/login.html'));
    });
    app.post('/auth', function(request, response) {     
        var username = request.body.username;//getting the username from the request
        var password = request.body.password;//getting the password from the request
    db.run('Insert into Credentials(Username,Password) Values(?),(?)',[username,password],function(error){});
    response.end();
    });
    app.listen(3000);//port number is mentioned