64,642
社区成员
发帖
与我相关
我的任务
分享
#pragma once
#include"mysql_connection.h"
#include"mysql_driver.h"
#include"mysql_error.h"
#include <cppconn/driver.h>
#include <cppconn/exception.h>
#include <cppconn/resultset.h>
#include <cppconn/statement.h>
#include<iostream>
using namespace std;
int main()
{
sql::mysql::MySQL_Driver *driver = NULL;
sql::Connection *conn = NULL;
sql::Statement *stmt = NULL;
sql::ResultSet *res = NULL;
try
{
driver = sql::mysql::get_mysql_driver_instance();
conn = driver->connect("tcp://localhost:3306/ygx", "root", "123456");
cout << "连接成功!" << endl;
}
catch (const std::exception&)
{
cout << "连接失败!" << endl;
goto END;
}
try
{
stmt = conn->createStatement();
stmt->execute("set character set gbk");
res = stmt->executeQuery("select * from test");
}
catch (const std::exception&)
{
cout << "查询失败!" << endl;
goto END;
}
cout << "查询成功!" << endl;
try
{
if (res->next())
{
cout << res->getString("姓名").c_str() << endl;
}
}
catch (const std::exception&)
{
cout << "显示失败!" << endl;
goto END;
}
END:
delete res;
delete stmt;
delete conn;
return 0;
}
stmt->execute("set character set gbk");
上面这条语句里设置的是 访问服务端时需要使用的编码方式,你的服务端使用的是utf8,你把这里改成utf8试试。下面是我测试用的代码:#include <iostream>
#include "mysql.h"
using namespace std;
int main()
{
MYSQL conn;
int res;
mysql_init(&conn);
if(mysql_real_connect(&conn,"localhost","root","","tboy",0,NULL,CLIENT_FOUND_ROWS))
{
res = mysql_query(&conn, "set names utf8");
// res = mysql_query(&conn,"insert into test values('today','编码测试语句,无乱码即为测试成功')");
res = mysql_query(&conn,"select * from test");
if(res)
{
cout << "error,res:" << res << endl;
}
else
{
MYSQL_RES *result = mysql_store_result(&conn);
if (result)
{
int num_fields = mysql_num_fields(result);
int num_rows=mysql_num_rows(result);
for(int i=0;i<num_rows;i++)
{
MYSQL_ROW row=mysql_fetch_row(result);
if(row<0) break;
for(int j=0;j<num_fields;j++)
{
cout<<row[j]<<"\t";
}
cout<<endl;
}
}
}
mysql_close(&conn);
mysql_library_end();
}
else
cout << "connect error!" << endl;
return 0;
}