首先要修改real_connect
//CLIENT_MULTI_STATEMENTS 支持多条sql语句
if (!mysql_real_connect(&mysql,host, user, pass, db, 3306, 0,CLIENT_MULTI_STATEMENTS))
执行sql语句立刻返回,但语句并没有全部执行好,需要获取结果。注意他不是事务,需要一次次返回,事务的话是执行完之后给结果
多个返回结果要用mysql_next(&mysql)
不妨使用do{}while{}
if (!mysql_real_connect(&mysql,host, user, pass, db, 3306, 0, CLIENT_MULTI_STATEMENTS))
{
cout << "mysql connect failed!" << mysql_error(&mysql) << endl;
}
else
{
cout << "mysql connect success!" << endl;
}
string sql = "";
// ... ... 这里是获得sql语句,不展开写了
//执行sql语句立刻返回,但语句并没有全部执行好,需要获取结果
//把sql整个发送给mysql server,server一条条执行,返回结果
int re = mysql_query(&mysql, sql.c_str());
if (re != 0)
{
cout << "mysql_query failed!" << mysql_error(&mysql) << endl;
}
//有多个返回结果
do
{
cout << "[result]";
MYSQL_RES * result = mysql_store_result(&mysql);
if (result) //SELECT
{
cout << "SELECT mysql_num_rows = " << mysql_num_rows(result) << endl;
mysql_free_result(result);
}
else // INSERT UPDATE DELETE CREATE DROP truncate
{
// SELECT 出错 有字段无结果
if (mysql_field_count(&mysql) > 0)
{
cout << "Not retrieve result! " <<mysql_error(&mysql)<< endl;
}
else //INSERT UPDATE DELETE CREATE DROP truncate
{
//等待服务器的处理结果
cout << mysql_affected_rows(&mysql) << " rows affected!" << endl;
}
}
}
//取下一条结果 0表示有结果
while (mysql_next_result(&mysql) == 0);
{
sql = "select * from t_image";
int re = mysql_query(&mysql, sql.c_str());
if (re != 0)
{
cout << "mysql_query failed!" << mysql_error(&mysql) << endl;
}
}