使用SqliteModernCpp的Sqlite更新查询

jucafojl  于 2022-12-13  发布在  SQLite
关注(0)|答案(2)|浏览(158)

我使用的是SqliteModernCpp库。我有一个数据访问对象模式,包括以下函数:

void movie_data_access_object::update_movie(movie to_update)
{
    // connect to the database
    sqlite::database db(this->connection_string);

    // execute the query
    std::string query = "UPDATE movies SET title = " + to_update.get_title() + " WHERE rowid = " + std::to_string(to_update.get_id());
    db << query;
}

实际上,我想更新数据库中的记录,该记录的rowid(PK)具有对象to_update在其参数(由get_id()返回)中具有的值。
此代码产生SQL逻辑错误。导致此错误的原因是什么?

l3zydbqr

l3zydbqr1#

结果发现,所创建的查询字符串中缺少单引号(')。该行应为:

std::string query = "UPDATE movies SET title = '" + to_update.get_title() + "' WHERE rowid = " + std::to_string(to_update.get_id());
ocebsuys

ocebsuys2#

由于github上的官方文档中没有UPDATE示例,这就是UPDATE查询应该如何用预准备语句和绑定来实现

#define MODERN_SQLITE_STD_OPTIONAL_SUPPORT
#include "sqlite_modern_cpp.h"

struct Book {
    int id;
    string title;
    string details;

    Book(int id_, string title_, string details_):
        id(std::move(id_)),
        title(std::move(title_)),
        details(std::move(details_)) {}
}

int main() {
    Book book = Book(0, "foo", "bar")

    sqlite::database db("stackoverflow.db");

    // Assuming there is a record in table `book` that we want to `update`
    db <<
    " UPDATE book SET "
    "   title   = ?, "
    "   details = ?  "
    " WHERE id = ?; "
    << book.title
    << book.details
    << book.id;

    return 0;
}

相关问题