C語言調用mysql的預存程序,調用mysql預存程序

來源:互聯網
上載者:User

C語言調用mysql的預存程序,調用mysql預存程序
本篇文章講解C語言調用mysql資料庫的預存程序的方法

下面假設有一張sc表,儲存學生選課記錄,有課程號,學號,平時分,卷面分,總分。
建立資料庫表過程:
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 < 0 || x > 100 ) THEN      SET t = -1;      LEAVE LABEL_PROC;  END IF;  IF ( y < 0 || 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 <stdio.h>#include "mysql.h"int 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;}

著作權聲明:本文為博主原創文章,未經博主允許不得轉載。

相關文章

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.