【问题标题】:Sqlite3 putting input field values into insert statementSqlite3 将输入字段值放入插入语句
【发布时间】:2019-01-11 20:09:45
【问题描述】:

我有 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:没有这样的列:患者姓名。

【问题讨论】:

  • 你的数据库架构是什么?它说表 info 没有列 Name
  • 很抱歉我写错了错误信息。实际的错误信息如下: SQLITE_ERROR: no such column: patientName。 @AritraChakraborty
  • 问题是你正在运行一个文字 SQL 字符串而没有替换变量值。大多数数据库会将其解释为从名为 patientName 的字段中获取值的指令,这显然不是你想要什么。尝试此页面上的“插入多条记录”部分:w3schools.com/nodejs/nodejs_mysql_insert.asp(显然,您只需要一条记录。
  • 当我在 w3school 中尝试示例时,错误变为:SQLITE_ERROR: 1 values for 4 columns @GregHNZ

标签: javascript node.js sqlite electron


【解决方案1】:

这看起来很愚蠢,但是您没有用引号括起值,也没有评估变量。 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}`);
});

【讨论】:

    猜你喜欢
    • 2016-09-01
    • 2016-07-14
    • 2022-01-13
    • 1970-01-01
    • 1970-01-01
    • 2017-02-11
    • 2019-01-12
    • 1970-01-01
    • 2020-10-14
    相关资源
    最近更新 更多