Node.js:SQLITE_ERROR:“ $ entry”附近:语法错误

时间:2018-12-10 13:13:21

标签: node.js sqlite

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

index.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:“ $ entry”附近:语法错误

我在这里可以做什么?

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

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

1 个答案:

答案 0 :(得分:0)

INSERT的正确语法是:

INSERT INTO entries(entry) VALUES ($entry)

(即使值只有一个,也将用括号括起来)