gpt4 book ai didi

c++ - 如何以编程方式设置 Sqlite PRAGMA 选项(即 "primary_key = On")?

转载 作者:行者123 更新时间:2023-11-30 05:39:28 25 4
gpt4 key购买 nike

我有一个使用以下命令行连接到 Sqlite3 的 C++ 程序:

int ret = sqlite3_open("databasefilename", &dbHandler);

打开数据库后,我需要启用 PRIMARY_KEYS,就像我使用普通 SQL 所做的那样:

sqlite> PRAGMA foreign_keys = ON;

是否有允许我执行此操作的 C++ 单一命令?我知道在 PHP 上我们可以使用:

        $service = new \Sqlite3($filename);
$service->enforceForeignKeys(true);

C++ 中有类似的东西吗?

最佳答案

In the C/C++ API for SQLite ,外键约束强制选项在您对 sqlite3_db_config() 的调用中指定:

sqlite3* db;
int err = sqlite3_open( "databaseFileName", &db );
if( err != SQLITE_OK ) /* die */

int fkeyConstraintsEnabled;
err = sqlite3_db_config( db, SQLITE_DBCONFIG_ENABLE_FKEY, /* either 0 or 1 to disable/enable constraints */, &fkeyConstraintsEnabled );
if( err != SQLITE_OK ) /* die */

printf( "Constraints now enabled: %d\r\n", fkeyConstraintsEnabled );

可以想象,您可以用 C/C++ 编写一个函数来包装它:

void enforceForeignKeys( sqlite3* db, bool enforceForeignKeyConstraints ) {

int expectedNewValue = enforceForeignKeyConstraints ? 1 : 0;
int actualNewValue;

int err = sqlite3_db_config( db, SQLITE_DBCONFIG_ENABLE_FKEY, expectedNewValue, &actualNewValue);
if( err != SQLITE_OK ) throw err;
if( actualNewValue != expectedNewValue ) throw SOME_USER_DEFINED_ERROR;
}

关于c++ - 如何以编程方式设置 Sqlite PRAGMA 选项(即 "primary_key = On")?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32342615/

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