Delphi sqlite3_db_config() 的用法

Delphi usage of sqlite3_db_config()

我正在尝试通过 sqlite3_db_config()SQLITE_DBCONFIG_MAINDBNAME 选项设置为自定义选项,但我在 Delphi 10.3 中仍然遇到这些指针的问题。连接运行良好,但后来的 PRAGMA database_list returns 不是我之前放入函数中的内容。第三个参数是我正在试验的,它是可变参数的一部分:

// bind method to sqlite3.dll:
sqlite3_db_config: function (ppDb: Psqlite3; op: Integer): Integer; cdecl varargs;

...

var
  FMainDbName: String;
begin
  FMainDbName := 'chinook';
  // shows "" (empty string)
  FLib.sqlite3_db_config(FHandle, SQLITE_DBCONFIG_MAINDBNAME, PAnsiChar(UTF8Encode(FMainDbName)));
  // shows the first character only: "c"
  FLib.sqlite3_db_config(FHandle, SQLITE_DBCONFIG_MAINDBNAME, PChar(FMainDbName));
end;

SQLite 文档说:

SQLITE_DBCONFIG_MAINDBNAME

This option is used to change the name of the "main" database schema. The sole argument is a pointer to a constant UTF8 string which will become the new schema name in place of "main". SQLite does not make a copy of the new main schema name string, so the application must ensure that the argument passed into this DBCONFIG option is unchanged until after the database connection closes.

那么,我需要如何格式化 sqlite3_db_config 的第三个参数?

UTF8Encode 为其 return 值创建一个临时字符串。您必须将该值存储在具有足够长生命周期的变量中:

var
  MainDBNameUTF8: UTF8String;

...
MainDBNameUTF8 := ...;
sqlite3_db_config(FHandle, SQLITE_DBCONFIG_MAINDBNAME, PAnsiChar(MainDBNameUTF8));