最近编写控制点库的几何精校正中使用SQLite来管理控制点,在使用过程中发现SQLite发现不支持中文路径,打开中文路径的数据库在查询的时候提示“no such table: ***”,很是郁闷,几经波折发现原来要把中文路径转成Utf-8的编码才可以。
在转换的时候考虑到跨平台的问题,于是使用libiconv库来转换。示例代码如下
#include <stdio.h>
#include <stdlib.h>
#include <string>
using namespace std;
#include <iconv.h> //编码转换库
#include <sqlite3.h> //SQLite3库
#define OUTLEN 255 //文件路径长度
//代码转换:从一种编码转为另一种编码
int code_convert(char *from_charset, char *to_charset, char *inbuf, size_t inlen, char *outbuf, size_t outlen)
{
iconv_t cd;
char **pin = &inbuf;
char **pout = &outbuf;
cd = iconv_open(to_charset,from_charset);
if (cd==0)
return -1;
memset(outbuf,0,outlen);
if (iconv(cd,pin,&inlen,pout,&outlen)==-1)
return -1;
iconv_close(cd);
return 0;
}
//UNICODE码转为GB2312码
int u2g(char *inbuf, size_t inlen, char *outbuf, size_t outlen)
{
return code_convert("utf-8","gb2312",inbuf,inlen,outbuf,outlen);
}
//GB2312码转为UNICODE码
int g2u(char *inbuf, size_t inlen, char *outbuf, size_t outlen)
{
return code_convert("gb2312","utf-8",inbuf,inlen,outbuf,outlen);
}
//执行SQL语句回调函数
static int _sql_callback(void* pUsed, int argc, char** argv, char** ppszColName)
{
for(int i=0; i<argc; i++)
{
printf("%s = %s/n", ppszColName[i], argv[i]==0 ? "NULL" : argv[i]);
}
return 0;
}
void main()
{
char *in_gb2312 = "D://控制点库//GCPDB.3sdb";
char *in_gbUTF8 = NULL;
char out[OUTLEN];
//gb2312码转为unicode码
g2u(in_gb2312,strlen(in_gb2312),out,OUTLEN);
printf("gb2312-->unicode out=%s /n",out);
const char* pszSql = "select id, name from gcp where id = 10;";
int iRet = 0;
sqlite3 *pDb = NULL;
char * pErrMsg = NULL;
iRet = sqlite3_open(out, &pDb);
if(iRet != SQLITE_OK)
{
fprintf(stderr, "无法打开数据库:%s", sqlite3_errmsg(pDb));
return;
}
iRet = sqlite3_exec(pDb, pszSql, _sql_callback, 0, &pErrMsg);
if(iRet != SQLITE_OK)
{
fprintf(stderr, "SQL Error %s/n", pErrMsg);
sqlite3_free(pErrMsg);
return;
}
iRet = sqlite3_close(pDb);
pDb = NULL;
system("pause");
}
希望对使用SQLite和Libiconv的童鞋们有所帮助!