sqlite3 打开中文路径失败

前阵子在跨平台中用了sqlite3,发现数据库存在中文路径下在Windows下表现异常,然后在android、iOS、Mac下表现正常,后发现与编码有关,解决方法记录下来免得忘记

出问题的原因在于filename 需要UTF-8

SQLITE_API int sqlite3_open(
       const char *filename,   /* Database filename (UTF-8) */
       sqlite3 **ppDb          /* OUT: SQLite db handle */
);

在linux平台下,系统编码是utf8,很少出现问题,但是windows平台下,如果数据库文件名称或路径有中文,通常会出现错误。其实这是sqlite3_open函数的问题,该函数要求文件名称的参数必须是utf8。

解决办法如下:

1.

中文Windows平台默认字符编码是gbk,可以使用sqlite3_open16代替sqlite3_open,需要配置Vs为字符集:使用 Unicode 字符集,包含头文件#include <Windows.h>或者<tchar.h>。

然后使用sqlite3_open16(TEXT("xxxx"), db);

2.

调用sqlite3,mbcs和utf8之间转换的函数:sqlite3_win32_mbcs_to_utf8

如下:

#if defined(WIN32)	
    int ret = sqlite3_open(sqlite3_win32_mbcs_to_utf8("xxx"), &db);
#else
#endif	

猜你喜欢

转载自blog.csdn.net/quanhaoH/article/details/128382380