mysql_real_query(&mysql, sql, strlen(sql)); //多了一个长度
mysql_query(&mysql, sql);
1、mysql_real_query sql语句中可以包含二进制数据,调用的时候多一个strlen
2、mysql_query sql语句只能是字符串 ,当数据里有0的时候,直接就停了
调用的时候 ***多次调用会出现
//Commands out of sync; you can't run this command now
//执行语句后,必须获取结果集,并且清理,要不然会报错
//遍历和清理数据集
MYSQL_ROW row;
while (row=mysql_fetch_row(result))
{
//获取长度
unsigned longlens= mysql_fetch_lengths(result);
cout<<lens[0] << "[" << row[0] << "]" << "[" << row[1] << "]" << "[" << row[2] <<"]" << endl;
}
//清理结果集
mysql_free_result(result);
测试代码
点击查看代码
#includeint main()
{
const char* host = "127.0.0.1";
const char* user = "root";
const char* password = "990107Wjl@";
const char* database = "database_test";
int port = 3306;
MYSQL mysql;
mysql_init(&mysql);
mysql_library_init(0, NULL, NULL);
//防止乱码
mysql_options(&mysql, MYSQL_SET_CHARSET_NAME, "GBK");
if (!mysql_real_connect(&mysql, host, user, password, database, port, NULL, 0))
{
cout << "failed to connect" << host << mysql_error(&mysql) << endl;
}
else
{
cout << "successfully connected" << host <<endl;
}
//找user表
//1、执行SQL语句
const char* sql = "select * from student";
//或者 char*sql;
//mysql_real_query sql语句中可以包含二进制数据
//mysql_query sql语句只能是字符串
//0返回成功
int re = mysql_real_query(&mysql, sql, strlen(sql));
//re = mysql_query(&mysql, sql);
//Commands out of sync; you can't run this command now
//zhixingsql语句后,必须获取结果集,并且清理,要不然会报错
if (re != 0)
{
//如果执行失败
cout << "查询语句执行失败,失败原因:" << sql <<" " << mysql_error(&mysql) << endl;
}
else
{
cout << "查询语句执行成功!"<< endl;
}
//获取结果集
//1 mysql_use_result不实际读取
//2 mysql_store_result //读取所有的数据,注意缓存大小 MYSQL_OPT_MAX_ALLOWED_PACKET 默认 64M
MYSQL_RES* result = mysql_use_result(&mysql); //row_count=0
//MYSQL_RES* result = mysql_store_result(&mysql); //row_count=2
if (!result)
{
cout << "mysql_use_result failed" << mysql_error(&mysql);
}
//遍历和清理数据集
MYSQL_ROW row;
while (row=mysql_fetch_row(result))
{
//获取长度
unsigned long*lens= mysql_fetch_lengths(result);
cout<<lens[0] << "[" << row[0] << "]" << "[" << row[1] << "]" << "[" << row[2] <<"]" << endl;
}
//清理结果集
mysql_free_result(result);
mysql_close(&mysql);
mysql_library_end();
system("pause");
return 0;
}