天天看點

MYSQL存儲過程查詢傳回結果處理方法

一、mysql表建立語句

1.1  建立表

set foreign_key_checks=0;

drop table if exists `testproc`;

create table `testproc` (

  `id` int(4) not null,

  `name` varchar(100) default null,

  primary key (`id`)

) engine=innodb default charset=utf8;

1.2  插入資料

insert into `testproc` values ('1', '第一條記錄');

insert into `testproc` values ('2', 'efgh');

insert into `testproc` values ('3', 'ijklmn');

insert into `testproc` values ('4', 'zxvb');

insert into `testproc` values ('5', 'uiop');

insert into `testproc` values ('6', '222');

insert into `testproc` values ('7', '8888');

insert into `testproc` values ('9', '第9條記錄');

insert into `testproc` values ('10', '第10條記錄');

insert into `testproc` values ('11', '第11條記錄');

insert into `testproc` values ('12', '第12條記錄');

1.3  建立存儲過程

create procedure test_proc_multi_select()

begin

         select * from testproc;

         select * from testproc where id=1;

end;

二、java相關代碼

注意要導入mysql包

import java.sql.connection;

import java.sql.drivermanager;

import java.sql.resultset;

import java.sql.sqlexception;

import com.mysql.jdbc.callablestatement;

public class test1 {

public static final string dbdriver = "com.mysql.jdbc.driver";

public static final string dburl = "jdbc:mysql://127.0.0.1:3306/test1";

public static final string dbuser = "root";

public static final string dbpass = "123456";

public static void main(string[] args) {

connection con = null;

callablestatement cs;

try {

        class.forname(dbdriver);

        con = drivermanager.getconnection(dburl, dbuser, dbpass);

        string sql = "{call test_proc_multi_select()}";

        cs = (callablestatement) con.preparecall(sql);

        boolean hadresults = cs.execute();

        int i = 0;

        while (hadresults) {

            system.out.println("result no:----" + (++i));

            resultset rs = cs.getresultset();

            while (rs != null && rs.next()) {

            int id1 = rs.getint(1);

            string name1 = rs.getstring(2);

            system.out.println(id1 + ":" + name1);

            }

        hadresults = cs.getmoreresults(); // 檢查是否存在更多結果集

        }

} catch (classnotfoundexception e) {

        e.printstacktrace();

} catch (sqlexception e) {

} finally {

    try {

        con.close();

    } catch (sqlexception e) {

    }

}

MYSQL存儲過程查詢傳回結果處理方法