调用存储过程其实很简单,这个的难点而是在于存储过程的编写。本节只是简单介绍一下jdbc如何调用存储。
主要内容如下
CallableStatement(从PreperedStatement扩展来)
cs = connection.prepareCall(“{call psname(?,?,?)}”);
cs.setXXX(i, xxxx);
cs.executeUpdate();
下面以向数据库插入一条数据为例:
public class PsTest {
/**
* @param args
* @throws SQLException
*/
public static void main(String[] args) throws SQLException {
// TODO Auto-generated method stub
System.out.println(ps());
}
static int ps() throws SQLException{
Connection conn=null;
CallableStatement cs=null;
ResultSet rs=null;
Date date=new Date();
int i;
try{
conn=jdbcUtils.getConnection();//创建连接
String sql="{call addUser(?,?)}";
cs=conn.prepareCall(sql);
cs.setString(1, "jack");
cs.setFloat(2, 1000);
i=cs.executeUpdate();
}
finally{
jdbcUtils.free(conn, cs, rs);//释放资源
}
return i;
}
}
批处理
static int[] batchTest() throws SQLException{
Connection conn=null;
PreparedStatement ps=null;
ResultSet rs=null;
int[] i=null;
try{
conn=jdbcUtils.getConnection();
String sql="insert into T_Users(name,birthday,money) values(?,?,?)";
ps=conn.prepareStatement(sql);
for(int n=0;n<1000;n++){
ps.setString(1, "batch name"+n);
ps.setDate(2, new Date(System.currentTimeMillis()));
ps.setFloat(3, 100+n);
ps.addBatch();
}
i= ps.executeBatch();
}
finally{
jdbcUtils.free(conn, ps, rs);
}
return i;
}