SQlite Chinese path solution

Reposted from: https://blog.csdn.net/yuan697/article/details/7837982

SQlite3 is a very easy-to-use lightweight database, but the sqlite3_open function does not support Chinese paths. Searching online shows that it needs to be converted to UTF8-encoded strings to be parsed correctly.

Generally, there are two processes of converting Ansi strings to Unicode strings, and then converting Unicode strings to UFT8. See the two functions as follows:

// 将ansi字符串转换成UNICODE
LPWSTR MultiByteToUnicode(char* szText)
{
	int nLength,nLen;
	wchar_t *pBuffer;
 
	nLen = (int)strlen(szText);
	nLength = MultiByteToWideChar(CP_ACP, 0, szText, nLen, NULL, 0);
	pBuffer = new wchar_t[nLength+1];
	MultiByteToWideChar(CP_ACP, 0, szText, nLen, (LPWSTR)pBuffer, nLength);
	pBuffer[nLength] = 0;
	return pBuffer;
}
// 将UNICODE字符串转换成UTF8
LPSTR UnicodeToUTF8(LPWSTR szText)
{
	char *pBuffer;
	int nLength;
	int nLen;
	nLen = (int)wcslen(szText);
	// 获取转换后的字符串长度
	nLength = WideCharToMultiByte(CP_UTF8, 0, szText, nLen, NULL, 0, 0, 0);
	int rc = GetLastError();
	pBuffer = new char[nLength + 1];
	// 进行字符转换
	WideCharToMultiByte(CP_UTF8, 0, szText, nLen, pBuffer, nLength, 0, 0);
	pBuffer[nLength] = 0;
	return pBuffer;
}

In this way, the Chinese path can be easily analyzed.

sqlite3 * pDB;
// 打开一个数据库,如果改数据库不存在,则创建一个名字为databaseName的数据库文件
char szFileName[MAX_PATH] = "E:\\中文路径\\test.db";
WCHAR * pWideFile = MultiByteToUnicode(szFileName);
char * pUTF8File = UnicodeToUTF8(pWideFile);
int rc = sqlite3_open(pUTF8File, &pDB);

Guess you like

Origin blog.csdn.net/auccy/article/details/130829267