首页 > 解决方案 > Node.js:SQLITE_ERROR:“$entry”附近:语法错误

问题描述

index.js:

var express = require('express');
var server = express();
var bodyParser = require('body-parser');

server.use(express.static('public'));
server.use(bodyParser.json());

const sqlite3 = require('sqlite3').verbose();
let db = new sqlite3.Database('./db.db', sqlite3.OPEN_READWRITE, (err) => {
  if (err) {
    console.error(err.message);
  }
  console.log('Connected to the database.');
});

server.post('/saveentry', (req, res) => {
    db.run("INSERT INTO entries(entry) VALUES $entry", req.body, function(err) {
    if (err) {
      return console.log(err.message);
    }
    // get the last insert id
    console.log(`A row has been inserted with rowid ${this.lastID}`);
    });
    res.send("Eintrag gespeichert");
    });

server.listen(80, 'localhost');

索引.html:

<html>
    <head>
        <title>Gästebuch</title>
    </head>
    <body>
        <div id="guestbook"></div>
        <input type="text" id="entry" name="entry">
        <button id="submit">Senden</button>

        <script
        src="https://code.jquery.com/jquery-3.3.1.min.js"
        integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8="
        crossorigin="anonymous"></script>
        <script>
            $('#submit').click(function() 
            {
                var formData = {
                $entry: $("#entry").val()
                }
                $.ajax({
                    type: 'POST',
                    url: '/saveentry',
                    data: JSON.stringify(formData),
                    dataType: "text",
                    contentType : "application/json",
                    success: function (data) {
                        console.log(data);
                    }
                });
            });
        </script>
    </body>
</html>

单击“Senden”按钮时,在控制台返回错误:SQLITE_ERROR: near "$entry": syntax error

我可以在这里做什么?

这两个链接可能会有所帮助:

https://github.com/mapbox/node-sqlite3/wiki/API#databaserunsql-param--回调 http://www.sqlitetutorial.net/sqlite-nodejs/insert/

标签: node.jssqlite

解决方案


an 的正确语法INSERT是:

INSERT INTO entries(entry) VALUES ($entry)

(值周围的括号,即使只有一个)


推荐阅读