大龙的博客

常用链接

统计

最新评论

MySQL一次执行多条语句的实现及常见问题(C API Commands out of sync; you can't run this command now)

通常情况MySQL出于安全考虑不允许一次执行多条语句(但也不报错,很让人郁闷)。MySQL是支持在单个查询字符串中指定多语句执行的,使用方法是给链接指定参数:

  1. //链接时设定  
  2. mysql_real_connect( ..., CLIENT_MULTI_STATEMENTS );  
  3. //或者  
  4. //中途指定  
  5. mysql_set_server_option( mysql, MYSQL_OPTION_MULTI_STATEMENTS_ON ); //mysql是连接的名称  

当使用执行多语句功能后,一定要读完整个resault集,否则会出现错误:Commands out of sync; you can't run this command now

官方推荐的执行语句是这样的:

 

  1. do  
  2. {  
  3.     /* Process all results */  
  4.     ...    
  5.     printf( "total affected rows: %lld", mysql_affected_rows( mysql ) );  
  6.     ...  
  7.   
  8.     if( !( result  mysql_store_result( mysql ) ) )  
  9.     {  
  10.         printf( stderr, "Got fatal error processing query\n" );  
  11.         exit(1);  
  12.     }  
  13.   
  14.     process_result_set(result); /* client function */  
  15.     mysql_free_result(result);  
  16. }while( !mysql_next_result( mysql ) );  

如果仅仅是插入等不需要返回值的SQL语句,也一样得读完整个resault集并释放,最小化的写法:

  1. do  
  2. {  
  3.     result = mysql_store_result( mysql );  
  4.     mysql_free_result(result);  
  5. }while( !mysql_next_result( mysql ) );  

posted on 2010-08-05 02:55 大龙 阅读(5078) 评论(1)  编辑 收藏 引用

评论

# re: MySQL一次执行多条语句的实现及常见问题(C API Commands out of sync; you can't run this command now) 2011-06-20 09:58 unlocked cell phones

请问下php有没有可能实现这样的模式。
$sql = "INSERT INTO test VALUES ('3', 'test2', '25', 'male');
INSERT INTO test2 VALUES ('4', 'test3', '18', 'female');";

$query = mysql_query($sql);  回复  更多评论   


只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理