Mysql C API調用存儲過程的總結

1. mysql table mysql

create table if not exists hwg_data_20151110
(
	id int primary key auto_increment,
	dev_type smallint unsigned not null,
	dev_id	 smallint unsigned not null,
	data_time datetime not null,
	data_time_ms smallint unsigned,
	data_time_us smallint unsigned, 
	yc_ac_ia smallint unsigned, 
	yc_ac_ic smallint unsigned, 
	yc_ac_in smallint unsigned, 
	yx1 smallint unsigned, 
	yx2 smallint unsigned, 
	freq smallint unsigned,
	tmp1 smallint unsigned, 
	tmp2 smallint unsigned, 
	tmp3 smallint unsigned
);
2. procedure
drop procedure if exists proc_get_newest_yc;
delimiter //

/*
*@brief 祿帽脠隆脳卯脨脗脪攏虜芒脢媒戮脻
*
*
*/
create procedure ca9100db.proc_get_newest_yc
(
	OUT myval float
)
begin
	declare mydate varchar(8);
	declare date_str varchar(17);
    declare sqlstr varchar(128);
    
	select date_format(current_date(), '%Y%m%d') into mydate;
	select concat('hwg_data_',mydate) into date_str;
    /*select date_str;*/
    set @sqlstr = concat('', 'select yc_ac_ia from ');
	set @sqlstr = concat(@sqlstr,date_str);
    set @sqlstr = concat(@sqlstr,'');
    select @sqlstr into sqlstr;
    prepare sqlstr from @sqlstr;
    execute sqlstr;
end
3. mysql c api調用
void DataServices::data_dispatcher_init()
{
	string query_tbl_str;
	string tbl_name;
	string query_str;
	MYSQL_ROW row;
	MYSQL_RES *res;
	unsigned char has_the_tbl = 0;
	int ret;
	string select_str;

	if (!mysql_real_connect(&mysql, this->mysql_host.c_str(), 
		this->mysql_user.c_str(), this->mysql_pwd.c_str(), this->mysql_dbname.c_str(), 
		0, NULL, CLIENT_MULTI_STATEMENTS)) {
		mysql_close(&mysql);
		exit(1);	
	}

	query_str = "call proc_get_newest_yc\(\@yc_ia\)";
	ret = mysql_real_query(&mysql, query_str.c_str(), (unsigned long)query_str.length());
	//ret = mysql_query(&(this->mysql), query_str);
	res = mysql_store_result(&mysql);
	while((row = mysql_fetch_row(res))) {
		printf("[%s]\n", row[0]);
	}
}

這裏須要特別注意一點: sql

在運行mysql_real_query/mysql_query執行存儲過程的時候可能會返回1,其錯誤消息爲 "Procedure myprocedure can't return a result set in the given context." api

緣由:與mysql_set_server_option() & mysql_real_connect()有關,mysql_real_connect函數的最後一個參數爲client_flag,默認咱們設置爲0,但存儲過程是在同一字符串中執行多個語句的,因此該參數須要修改默認值爲CLIENT_MULTI_STATEMENTS。 函數

參考:
http://stackoverflow.com/questions/2350823/problems-calling-mysql-stored-procedures-from-c-api fetch

相關文章
相關標籤/搜索