最近在檢查一方法時發現程序執行SQL查詢時非常慢,但使用PLSQL DEV工具執行查詢語句又很快。
看以下代碼:
public boolean isExistSonoByStoreCode(String storeCode, String soNo, String billId)
{
StringBuffer sql = new StringBuffer();
sql.append("select bill_id, so_no from store_in_head where store_code = ? and UPPER(so_no) = UPPER(?) ");
DBUtil dbu = null;
PreparedStatement preStmt = null;
ResultSet rs = null;
boolean isExistSono = false;
try
{
dbu = new DBUtil();
preStmt = dbu.getConnection().prepareStatement(sql.toString());
preStmt.setString(1, storeCode);
preStmt.setString(2, soNo);
rs = preStmt.executeQuery();
while (rs.next())
{
String oldBillId = rs.getString("bill_id");
if (!oldBillId.equalsIgnoreCase(billId))
{
isExistSono = true;
}
}
}
catch (Exception e)
{
log.error(e.getMessage(),e);
}
finally
{
try
{
rs.close();
}
catch (Exception e)
{
;
}
try
{
preStmt.close();
}
catch (Exception e)
{
;
}
closeDButil(dbu);
}
return isExistSono;
}
經DEBUG發現速度慢確實發生在查詢時,即執行rs = preStmt.executeQuery();時
一開始懷疑是語句使用UPER函數導致的,但是把語句修改爲不使用函數也一樣慢。。懷疑是使用了PreparedStatement 參數需要動態綁定問題,於是將PreparedStatement 改爲Statement ,執行卻很快,修改後的代碼如下:
public boolean isExistSonoByStoreCode(String storeCode, String soNo, String billId)
{
StringBuffer sql = new StringBuffer();
sql.append("select bill_id, so_no from store_in_head where store_code = '" + storeCode + "' and UPPER(so_no) = UPPER('"+ soNo +"') ");
DBUtil dbu = null;
Statement preStmt = null;
ResultSet rs = null;
boolean isExistSono = false;
try
{
dbu = new DBUtil();
preStmt = dbu.getConnection().createStatement();
rs = preStmt.executeQuery(sql.toString());
// preStmt.setString(1, storeCode);
// preStmt.setString(2, soNo);
// rs = preStmt.executeQuery();
while (rs.next())
{
String oldBillId = rs.getString("bill_id");
if (!oldBillId.equalsIgnoreCase(billId))
{
isExistSono = true;
}
}
}
catch (Exception e)
{
log.error(e.getMessage(),e);
}
finally
{
try
{
rs.close();
}
catch (Exception e)
{
;
}
try
{
preStmt.close();
}
catch (Exception e)
{
;
}
closeDButil(dbu);
}
return isExistSono;
}
字段類型:STORE_CODE CHAR(3),SO_NO VARCHAR2(100)
類似問題:http://bbs.csdn.net/topics/320181076