1.
當使用PreparedStatement\CallableStatement時,盡量使用它提供的setParams的方法。
下面是錯誤的方法:
CallableStatement cstmt = conn.prepareCall (
"{call getCustName (12345)}");
ResultSet rs = cstmt.executeQuery ();
下面是正確的方法:
CallableStatement cstmt - conn.prepareCall (
"{call getCustName (?)}");
cstmt.setLong (1,12345);
ResultSet rs = cstmt.executeQuery();
2.使用批量更新的方法
一般都是使用這樣的方法更新:
PreparedStatement ps = conn.prepareStatement(
"INSERT into employees values (?, ?, ?)");
for (n = 0; n < 100; n++) {
ps.setString(name[n]);
ps.setLong(id[n]);
ps.setInt(salary[n]);
ps.executeUpdate();
}
如果使用JDBC的高級功能的話,批量更新應該會有更高的效率:
PreparedStatement ps = conn.prepareStatement(
"INSERT into employees values (?, ?, ?)");
for (n = 0; n < 100; n++) {
ps.setString(name[n]);
ps.setLong(id[n]);
ps.setInt(salary[n]);
ps.addBatch();
}
ps.executeBatch();
3.正確使用ResultSet的GET方法
盡量不要使用諸如rs.getObject()這樣的方法,另外如果還要更高的效率的話,請使用rs.getString(1)這樣通過字段索引號的方式來取得字段值,而不是使用象rs.getString("UserName")這樣的方法來取得字段值。
4.取得剛增加的記錄的自動增加類型的字段的值
如果你的JDBC驅動支持的話,有一個很方便的方法可以取得自增字段的值,如下:
int rowcount = stmt.executeUpdate (
"insert into LocalGeniusList (name) values ('Karen')",
Statement.RETURN_GENERATED_KEYS);
ResultSet rs = stmt.getGeneratedKeys ();