建立数据库表过程:
create table class(
cno varchar(8) not null,
sno varchar(8) not null,
ordinary_score int,
last_score int,
all_score int
);
存储过程
由括号包围的参数列必须总是存在。如果没有参数,也该使用一个空参数列()。每个参数 默认都是一个in参数。要指定为其它参数,可在参数名之前使用关键词in(默认,可缺省) out或inout。
in参数是只传入
out参数是只传出
inout参数是既传入又传入,即双向传递
指定参数为in, out, 或inout 只对procedure是合法的。(function参数总是被认为是in参数)
建立存储过程,传入平时分x,卷面分y,平时分所占的比率pert,学号,课程号;建立过程如下
delimiter //create procedure cal_grade(x int,y int,out t int,pert float,s varchar(8),c varchar(8))label_proc:begin if ( x 100 ) then set t = -1; leave label_proc; end if; if ( y 100 ) then set t = -2; leave label_proc; end if; set t = round( x*pert + y*(1-pert) ); update sc set ordinary_score=x,last_score=y where sno=s and cno=c and tno=tn;end label_proc //delimiter ;
c语言调用
#include #include mysql.hint main(){ mysql *my_connection; mysql_res *res_ptr; mysql_row sqlrow; char buf[100]; my_connection = mysql_init (null); //下面连接的最后一个参数必须为client_multi_statements,不然就会报错select error: procedure *** can’t return a result set in the given context my_connection = mysql_real_connect (my_connection, localhost, root, root, test, 0, null, client_multi_statements); sprintf (buf, call cal_grade(%d,%d,@t,%f,%s,%s), 10, 10, 0.3, 123, 456); if ( mysql_query (my_connection, buf) ) sprintf (stderr, mysql_error (my_connection)); else { //获得返回参数@t,@t是传出参数 mysql_query (my_connection, select @t); res_ptr = mysql_store_result (my_connection); if (res_ptr) { sqlrow = mysql_fetch_row (res_ptr); if (!strcmp (sqlrow[0], -1)) printf (平时分不在范围之内\n); else if (!strcmp (sqlrow[0], -2)) printf (卷面分不在范围之内\n); else printf (总分为:%s\n, sqlrow[0]); } mysql_free_result (res_ptr); } mysql_close (my_connection); return 0;}
