gpt4 book ai didi

c++ - 在 bindValue(...) 函数中使用 select 语句 - Qt & SQLite

转载 作者:行者123 更新时间:2023-11-28 00:09:49 25 4
gpt4 key购买 nike

假设我有以下 SQLite 表定义:

create table test (id integer primary key, info integer);

和以下条目:

id  | info
----------
1 | 10
2 | 20
3 | 30

我想使用 Qt 的 QSqlQuery 类来prepare() 查询并使用 bindValue() 函数。

我想要实现的是

insert into test values (
( select id from test where ROWID = last_insert_rowid() )+100,
666
);

为了得到:

id  | info
----------
1 | 10
2 | 20
3 | 30
103 | 666

虽然它直接通过 QSqlQuery qry 对象 exec() 执行语句,但是这

//qry is set up correctly.
qry.prepare("insert into test values (?,?);");
qry.bindValue(0, "select id from test where ROWID = last_insert_rowid() )+100");
qry.bindValue(1,666);
qry.exec();

不起作用(数据类型不匹配)。

1) 我怎样才能使用 bindValue() 让它工作?

2) 在不使用 last_insert_rowid() 的情况下实现相同行为的最巧妙方法是什么?

3) 如果表到目前为止没有行,上面的代码将为 id 返回什么值?零?

最佳答案

1) 不能将 SQL 表达式绑定(bind)到“?”,这是绑定(bind)目的。忘了第一个“?”并且只绑定(bind)一个值:

qry.prepare("insert into test values ( (select id from test where ROWID = last_insert_rowid() )+?,?);");
qry.bindValue(0,100);
qry.bindValue(0,666);
qry.exec();

2) 如果你有整数主键列,sqlite last_insert_rowid() 将返回该列的值,所以你可以简单地写:

qry.prepare("insert into test values (last_insert_rowid()+?,?);");
qry.bindValue(0,100);
qry.bindValue(0,666);
qry.exec();

考虑到您的预期行为,这不会表现得像自动递增,因为有人可以在索引处插入一个值,这会导致您的下一次插入发生冲突。更安全的方法是增加最大值:

qry.prepare("insert into test values ( (select id from test order by id desc limit 1)+?,?);");
qry.bindValue(0,100);
qry.bindValue(0,666);
qry.exec();

3) 如果表是空的,这个select将返回null,并且null+100仍然是null,这将触发自动递增,因此插入 1。

关于c++ - 在 bindValue(...) 函数中使用 select 语句 - Qt & SQLite,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33747021/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com