2

I have an SQLite3 table with BLOB primary key (id):

CREATE TABLE item (
    id BLOB PRIMARY KEY,
    title VARCHAR(100)
);

In javascript models, the primary key (id) is represented as a Javascript string (one HEX byte per character):

var item = { 
    id: "2202D1B511604790922E5A090C81E169",
    title: "foo"
}

When I run the query below, the id parameter gets bound as a string. But I need it to be bound as a BLOB.

db.run('INSERT INTO item (id, title) VALUES ($id, $title)', {
    $id: item.id,
    $title: item.title
});

To illustrate, the above code generates the following SQL:

INSERT INTO item (id, title) VALUES ("2202D1B511604790922E5A090C81E169", "foo");

What I need is this:

INSERT INTO item (id, title) VALUES (X'2202D1B511604790922E5A090C81E169', "foo");
4

2 回答 2

1

显然,字符串需要转换为缓冲区:

db.run('INSERT INTO item (id, title) VALUES ($id, $title)', {
    $id: Buffer.from(item.id, 'hex'),
    $title: item.title
});
于 2018-03-20T12:53:33.147 回答
0

尝试将字符串转换为 blob:

INSERT INTO item(id, title) VALUES(CAST(id_string AS BLOB), 'foo');

另请注意,在 SQL 中引用字符串的正确方法是使用单引号。

于 2018-03-05T21:03:27.200 回答