首页 > 解决方案 > 无法将 sha256 哈希插入 SQLite3 表 - NodeJs

问题描述

我正在使用 SQLite3 和 NodeJs 创建一个 sha256 哈希表尝试插入整数和随机哈希时,出现以下错误。

{ Error: SQLITE_ERROR: no such column: e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855 errno: 1, code: 'SQLITE_ERROR' }

这是在表中创建和插入数据的来源

// * Create ~ Open Hashes Database
let db = new sqlite3.Database('./hashes.db', sqlite3.OPEN_READWRITE | sqlite3.OPEN_CREATE, (e => {
  if (e) {
    console.log('Failed to open/create hashes database')
  }

  console.log('Successfully opened / created')
}));

const hash = crypto.createHash('sha256').digest('hex');

// * 1 Create Database
db.run("CREATE TABLE hashes(seq INTEGER PRIMARY KEY, hash VARCHAR(255) NOT NULL)", (e) => {
  if (e) return console.log(e);
  console.log('Created database')
});

db.run(`INSERT INTO hashes VALUES (1, ${hash})`, (e) => {
  if (e) return console.log(e);
  console.log("successfully inserted", 1, hash);
})

第 1 列 (Seq) 只是一个顺序递增的整数 (1,2,3....),第二列是 VARCHAR 类型的散列。

标签: sqlnode.jssqlite

解决方案


请上帝使用参数而不是字符串插值将动态值传递给查询。对于与任何SQL 引擎交互的任何编程语言都是如此。字符串插值使您面临大量 sql 注入漏洞,请参阅https://bobby-tables.com/

这在节点 sqlite3 API 中有明确记录和推荐:

https://github.com/mapbox/node-sqlite3/wiki/API#databaserunsql-param--callback

      db.run("UPDATE tbl SET name = ? WHERE id = ?", "bar", 2);

这就好像值"bar"2分别代替了两个?


在您的情况下,这应该这样做:

db.run("INSERT INTO hashes VALUES (1, ?)", hash, (e) => {
  if (e) return console.log(e);
  console.log("successfully inserted", 1, hash);
})

它看起来更好,更容易,更安全。

请注意,我将反引号插值 `-string 更改为双引号 "-string。这是故意的。不要将值插值到 SQL 字符串中。


推荐阅读