2017年3月30日星期四

mysql中如何使用statement取得存储过程的OUT参数

按照通常的方法,只能通过变量+SELECT结果集来获得存储过程out参数的值,例如:
@out1:=0;
@out2:='';
call procedure_test_1(@out1, @out2);
select @out1, @out2;
如何不要使用多条语句而直接使用out参数的值呢?mysql的statement可以实现:
see:https://dev.mysql.com/doc/refman/5.7/en/c-api-prepared-call-statements.html

这里需要注意:
1. 先要绑定参数,然后执行;
2. 执行完后绑定结果
3. 执行mysql_stmt_next_result()后才能取得out参数的值
   如果存储过程中用了多个select, 则最后一个结果集才是out参数的值

see: https://dev.mysql.com/doc/refman/5.5/en/mysql-stmt-next-result.html
官方文档对于取得OUT参数做了详细的说明:
If a procedure has OUT or INOUT parameters, their values will be returned as a single-row result set following any other result sets. The values will appear in the order in which they are declared in the procedure parameter list.
最后,编译和链接的地方需要注意:
g++ -o test_procedure_2.o -c test_procedure_2.cpp -g -Wall -Werror `mysql_config --include`
g++ -o test_procedure_2 test_procedure_2.o `mysql_config --libs` -lpthread
使用mysql_config来获取相关的头文件和库,否则错误的头文件和库将导致:
  · 链接告警,see:http://www.cnblogs.com/chengxuyuancc/archive/2013/05/11/3072981.html
  · 执行时显示找不到:libmysql.so
  · 执行完全得不到正确的结果

最后的最后,如果链接使用:
g++ -o test_procedure_2 test_procedure_2.o `mysql_config --libs_r` -lpthread
  即采用动态方式链接,居然会出现:
     undefined reference to `mysql_stmt_next_result'
  神(la)奇(ji)!!!




没有评论:

发表评论