【问题标题】:Using a select statement in the bindValue(...) function - Qt & SQLite在 bindValue(...) 函数中使用 select 语句 - Qt & SQLite
【发布时间】:2016-02-18 05:43:35
【问题描述】:

假设我有以下 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()ing 语句起作用,但这个

//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 返回什么值?零?

【问题讨论】:

    标签: c++ qt sqlite qsqlquery bindvalue


    【解决方案1】:

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

    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) 如果你有整数主键列,sqlitelast_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。

    【讨论】:

    • 好吧,我是这么认为的...关于第 2 部分)有什么想法吗?
    • 好的,如果我只想处理最后插入的行,ROWIDlast_insert_rowid() 是要走的路吗?
    • @LCsa 我想我是在你接受我的问题后编辑的,你太不耐烦了。
    • 我并不急躁,我只是觉得从最初的问题来看它太过分了,并决定在你被它困扰之前再把它拿走。这次尝试显然失败了,但是,绝对没有伤害的意思! :-) 感谢您的更新,我将撤消问题中的更改!
    猜你喜欢
    • 2011-06-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-12-12
    • 1970-01-01
    相关资源
    最近更新 更多