SQLite3将输入字段值放入插入语句

时间:2018-08-03 22:55:03

标签: javascript node.js sqlite electron

我有4列的sqlite数据库

Name
Age
bloodGroup
lastdate 

以及4个输入字段和保存按钮,如下所示:

<input type="text" name="" id="patientName">
<input type="number" name="" id="PatientAge">
<input type="text" name="" id="PatientBloodGroup">
<input type="date" name="" id="PatientLastDate">
<button id="savebtn"> Save </button>

并且我使用下面的javascript代码获取输入值并将它们插入数据库的列中:

<script type="text/javascript">
    document.getElementById('savebtn').addEventListener('click', saveFunction);
    function saveFunction(){
        const sqlite3 = require('sqlite3').verbose();
        let db = new sqlite3.Database('./database_name');
        var patientName = document.getElementById('patientName').value;
        var patientAge = document.getElementById('patientAge').value;
        var patinetBloodGroup =   document.getElementById('patientBloodGroup').value;
        var PatientLastDate = document.getElementById('patientLastDate').value;

        db.run(`INSERT INTO info(Name, Age, bloodGroup, lastdate) VALUES(patientName, patientAge, patientBloodGroup, PatientLastDate), function(err) {
            if (err) {
                return console.log(err.message);
            }
            console.log(`A row has been inserted with rowid ${this.lastID}`);
        });
        db.close();
    } 
</script>

程序运行时会显示此错误消息:

  

SQLITE_ERROR:没有这样的列:PatientName。

1 个答案:

答案 0 :(得分:0)

这似乎很愚蠢,但是您没有将值用引号引起来,也没有对变量进行求值。 INSERT INTO查询将采用

的形式
INSERT INTO Customers (CustomerName, City, Country)
VALUES ('Cardinal', 'Stavanger', 'Norway');

因此将您的数据库查询更改为:

db.run(`INSERT INTO info(Name, Age, bloodGroup, lastdate) VALUES('${patientName}', '${patientAge}', '${patientBloodGroup}', '${PatientLastDate}')`), function(err) {
    if (err) {
        return console.log(err.message);
    }
    console.log(`A row has been inserted with rowid ${this.lastID}`);
});

现在,此代码显然容易受到SQL注入的影响。您应该使用准备好的声明

db.run(`INSERT INTO info(Name, Age, bloodGroup, lastdate) VALUES(?, ?, ?, ?)`, patientName, patientAge, patientBloodGroup, PatientLastDate), function(err) {
    if (err) {
        return console.log(err.message);
    }
    console.log(`A row has been inserted with rowid ${this.lastID}`);
});