//查询
result = stmt->executeQuery("select * from users");
while(result->next())
{
string username = result->getString("username");
string password = result->getString("password");
cout << utf2ansi(username) << " : " << password << endl;
}
//插入
string sql="insert into users(username,password) values('" + ansi2utf8(string("飞翔"))+ "','asdfgh')";
stmt->executeUpdate(sql);
//删除
sql="delete from users where id=4";
stmt->executeUpdate(sql);
//修改
sql="update users set password='hello' where username='" + ansi2utf8(string("沈健")) +"'";;
stmt->executeUpdate(sql);
查出来的数据需要转换成ANSI编码,传给mysql服务器的数据需要转换为unicode编码(mysql数据库中所建的数据库、表和字段采用utf-8编码)
下面是相应的转换函数
//将标准string(unicode)转换为string(ansi)
string utf2ansi(const string &src){
int nLen = MultiByteToWideChar( CP_UTF8, 0, src.data(), -1, NULL, NULL );
LPWSTR lpwsz = new WCHAR[nLen];
MultiByteToWideChar( CP_UTF8, 0, src.data(), -1, lpwsz, nLen );
int nLen1 = WideCharToMultiByte( CP_ACP, 0, lpwsz, nLen, NULL, NULL, NULL, NULL );
LPSTR lpsz = new CHAR[nLen1];
WideCharToMultiByte( CP_ACP, 0, lpwsz, nLen, lpsz, nLen1, NULL, NULL );
string str(lpsz);
delete []lpsz;
return str;
}
//将标准string(ansi)转换为string(unicode)
string ansi2utf8(const string &src){
int nLen = MultiByteToWideChar( CP_ACP, 0, src.data(), -1, NULL, NULL );
LPWSTR lpwsz = new WCHAR[nLen];
MultiByteToWideChar( CP_ACP, 0, src.data(), -1, lpwsz, nLen );
int nLen1 = WideCharToMultiByte( CP_UTF8, 0, lpwsz, nLen, NULL, NULL, NULL, NULL );
LPSTR lpsz = new CHAR[nLen1];
WideCharToMultiByte( CP_UTF8, 0, lpwsz, nLen, lpsz, nLen1, NULL, NULL );
string str(lpsz);
delete []lpsz;
return str;
}