javaJDBC(3)-获取主键、调用存储过程

说明:这里接上篇,使用前面总结的jdbcutil.java实现获取主键与调用存储过程


获取主键:


package cn.itcast.jdbc;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

import org.junit.Test;

import cn.itcast.util.JdbcUtil;


public class GetDBGenKeyDemo {

 /**
  * @param args
  */
 @Test
 public  void test() {
  Connection conn = null;
  PreparedStatement stmt = null;
  ResultSet rs = null;
  try{
   conn = JdbcUtil.getConnection();
   stmt = conn.prepareStatement("insert into t1 (name) values(?)");
   stmt.setString(1, "jh");
   stmt.executeUpdate();
   //以下获取生成的主键
   rs = stmt.getGeneratedKeys();
   if(rs.next()){
    System.out.print(rs.getInt(1));
    //System.out.println(rs.getInt(2));
    
   }
  }catch(Exception e){
   e.printStackTrace();
  }finally{
   JdbcUtil.release(rs, stmt, conn);
  }
 }

}


调用存储方法:

package cn.itcast.jdbc;

import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Types;

import org.junit.Test;

import cn.itcast.util.JdbcUtil;
/*这里的内容在数据库内执行

delimiter $$
CREATE PROCEDURE demoSp(IN inputParam VARCHAR(255),INOUT inOutParam VARCHAR(255))
BEGIN
SELECT CONCAT(‘welcom---‘,inputParam) into inOutParam;
END $$
delimiter ;
 */
//如何调用存储过程
public class InvokeProcedureDemo {
 @Test
 public  void test() {
  // TODO Auto-generated method stub
  Connection conn = null;
  CallableStatement stmt = null;
  ResultSet rs = null;
  try{
   conn = JdbcUtil.getConnection();
   stmt = conn.prepareCall("{call demoSp(?,?)}");
   stmt.setString(1, "to qingdao");
   stmt.registerOutParameter(2,Types.VARCHAR);
   stmt.execute();
   String value = stmt.getString(2);
   System.out.println(value);
  }catch(Exception e){
   e.printStackTrace();
  }finally{
   JdbcUtil.release(rs, stmt, conn);
  }
 }
}




javaJDBC(3)-获取主键、调用存储过程

上一篇:fast db 学习


下一篇:21分钟 MySQL 入门教程(转载!!!)