日期:2014-05-16  浏览次数:20476 次

JDBC学习(4)
Statement和PreparedStatement主要区别:
1、代码的可读性和可维护性。上面的例子可以看出。
2、PreparedStatement尽最大可能提高性能。
Statement每次执行sql语句,相关数据库都要执行sql语句的编译;PreparedStatement是预编译的,对于批量处理可以大大提高效率。

2)PrepareStatement(用于执行预编译的SQL语句)
PreparedStatement stmt = conn.prepareStatement("INSERT INTO Employee VALUES(?,?,?)"); //没有具体的值,只有?
Employee[] employees = ...; //Employee对象中存储了对应employee表中字段信息时
for(int i=0; i<employees.length; i++)
{
   stmt.setInt(1, employee[i].getId()); //参数的开始索引为1,不是0
   stmt.setString(2, employees[i].getName());
   stmt.setString(3, employees[i].getDepartment());
   stmt.addBatch();
}
int[] counts = stmt.executeBatch();

  3)CallableStatement (用于执行存储过程)

//创建CallableStatement
CallableStatement cstmt = conn.prepareCall( "{call TestData(?, ?)}"); cstmt.setInt(1,12);//设置第一个占位符“?”的值为12
cstmt.registerOutParameter(2, java.sql.Types.BIGINT); //注册输出参数
cstmt.execute(); //执行存储过程
int n = cstmt.getInt(1); //获取结果