MFC向MySQL数据库写入数据,中文乱码怎么解决???

时间:2022-06-22 07:06:30
RT,显示的界面如下:
MFC向MySQL数据库写入数据,中文乱码怎么解决???
显示数据库中原有的数据正常,但是写入的中文就是乱码,是不是需要进行字符编码的转换?请大神指教
我的代码如下:
//添加
void CAccessToMySQL_APPDlg::OnBnClickedBtnAdd()
{
// TODO: 在此添加控件通知处理程序代码
UpdateData(TRUE);
//CString m=L"INSERT INTO tdb_goods_brands VALUES('";
//CString m_sql=m+m_iID+L"','"+m_strBrand+L"')";
//char *my_sql=new char[100];
//WideCharToMultiByte(CP_ACP,0,m_sql.GetBuffer(),-1,my_sql,100,NULL,NULL);//Unicode转换成多字节字符串
CString strCate_id,strBrand_id,strPrice,strIsShow,strIsSaleoff;
GetDlgItemText(IDC_EDIT_CATE,strCate_id);
GetDlgItemText(IDC_EDIT_BRAND_NAME,strBrand_id);
GetDlgItemText(IDC_EDIT_PRICE,strPrice);
GetDlgItemText(IDC_EDIT_IS_SHOW,strIsShow);
GetDlgItemText(IDC_EDIT_IS_SALEOFF,strIsSaleoff);
int iCate_id=_wtoi(strCate_id.GetBuffer());
int iBrand_id=_wtoi(strBrand_id.GetBuffer());
int iIsShow=_wtoi(strIsShow.GetBuffer());
int iIsSaleoff=_wtoi(strIsSaleoff.GetBuffer());
double dPrice=_wtof(strPrice.GetBuffer());
char sql[300];
sprintf_s(sql,"INSERT INTO tdb_goods(goods_name,cate_id,brand_id,goods_price,is_show,is_saleoff) VALUES('%s',%d,%d,%f,%d,%d)",m_strBrand,iCate_id,iBrand_id,dPrice,iIsShow,iIsSaleoff);
//CString sql;
//sql.Format(L"INSERT INTO tdb_goods_brands(brand_name) VALUES('%s');",m_strBrand);
//char *my_sql=new char[100];
//WideCharToMultiByte(CP_ACP,0,sql.GetBuffer(),-1,my_sql,100,NULL,NULL);//Unicode转换成多字节字符串
if(mysql_query(sock,sql))
AfxMessageBox(L"添加失败!");
else
{
FreshList();
ClearEditCtrl();
AfxMessageBox(L"添加成功!");
}
}

5 个解决方案

#1


对电脑而言没有乱码,只有二进制字节;对人脑才有乱码。啊 GBK:0xB0 0xA1,Unicode-16 LE:0x4A 0x55,Unicode-16 BE:0x55 0x4A,UTF-8:0xE5 0x95 0x8A

#2


安装mysql数据库服务端指定字符集编码为utf-8
MFC向MySQL数据库写入数据,中文乱码怎么解决???
创建数据库也指定utf-8,如可用以下语句执行创建数据库:
CREATE DATABASE netdb CHARACTER SET 'utf8' COLLATE 'utf8_general_ci';

#3


CString 在 UNICODE编译模式下为 宽字体, 因此 %s 时不能直接使用

#4


字符集没设置好

#5



sprintf_s(sql,"INSERT INTO tdb_goods(CONVERT(CAST(goods_name AS BINARY) USING 'utf8'),cate_id,brand_id,goods_price,is_show,is_saleoff) VALUES('%s',%d,%d,%f,%d,%d)",m_strBrand,iCate_id,iBrand_id,dPrice,iIsShow,iIsSaleoff);

试下这样,转成UTF8编码,

#1


对电脑而言没有乱码,只有二进制字节;对人脑才有乱码。啊 GBK:0xB0 0xA1,Unicode-16 LE:0x4A 0x55,Unicode-16 BE:0x55 0x4A,UTF-8:0xE5 0x95 0x8A

#2


安装mysql数据库服务端指定字符集编码为utf-8
MFC向MySQL数据库写入数据,中文乱码怎么解决???
创建数据库也指定utf-8,如可用以下语句执行创建数据库:
CREATE DATABASE netdb CHARACTER SET 'utf8' COLLATE 'utf8_general_ci';

#3


CString 在 UNICODE编译模式下为 宽字体, 因此 %s 时不能直接使用

#4


字符集没设置好

#5



sprintf_s(sql,"INSERT INTO tdb_goods(CONVERT(CAST(goods_name AS BINARY) USING 'utf8'),cate_id,brand_id,goods_price,is_show,is_saleoff) VALUES('%s',%d,%d,%f,%d,%d)",m_strBrand,iCate_id,iBrand_id,dPrice,iIsShow,iIsSaleoff);

试下这样,转成UTF8编码,