当前所在位置:珠峰网资料 >> 计算机 >> 计算机等级考试 >> 正文
计算机二级辅导:JDBC调用MySQL5存储过程
发布时间:2010/3/13 9:19:50 来源:城市学习网 编辑:MOON
  JDBC调用MySQL5存储过程,过程有入参和出参,执行存储过程,并获取出参。
  MySQL5.1
  mysql-connector-java-5.1.10
  jdk1.5
  表
  create table user (
  id int(11) not null auto_increment,
  name varchar(50) not null,
  pswd varchar(50) default null,
  pic longblob,
  remark longtext,
  primary key (id)
  );
  DELIMITER $$
  DROP PROCEDURE IF EXISTS testprocedure $$
  CREATE DEFINER=`vcom`@`%` PROCEDURE testprocedure(in in_name varchar(20),in in_pswd varchar(20),out out_id bigint)
  BEGIN
  insert into user(name,pswd) values(in_name,in_pswd);
  select last_insert_id() into out_id;
  END $$
  DELIMITER ;
  import lavasoft.common.DBToolkit;
  import java.sql.CallableStatement;
  import java.sql.Connection;
  import java.sql.SQLException;
  import java.sql.Types;
  /**
  * JDBC调用MySQL5存储过程
  *
  */
  public class ProcedureTest {
  public static void main(String args) {
  testExeProcedure();
  }
  public static void testExeProcedure() {
  Connection conn = DBToolkit.getConnection();
  //创建调用存储过程的预定义SQL语句
  String sql = "{call testprocedure(?,?,?)}";
  try {
  //创建过程执行器
  CallableStatement cstmt = conn.prepareCall(sql);
  //设置入参和出参
  cstmt.setString(1, "wangwu");
  cstmt.setString(2, "111111");
  cstmt.registerOutParameter(3, Types.BIGINT); //注册出参
  cstmt.executeUpdate();
  //获取输出参数值(两种方式都行)
  Long id = cstmt.getLong(3);
  //Long id = cstmt.getLong("out_id");
  System.out.println("本次插入数据的id=" + id);
  } catch (SQLException e) {
  e.printStackTrace();
  } finally {
  DBToolkit.closeConnection(conn);
  }
  }
  }
  运行后,控制台:
  本次插入数据的id=1
  Process finished with exit code 0
  Java调用存储过程很容易,但是开发存储过程比较困难
  :
广告合作:400-664-0084 全国热线:400-664-0084
Copyright 2010 - 2017 www.my8848.com 珠峰网 粤ICP备15066211号
珠峰网 版权所有 All Rights Reserved