2012-05-24 38 views
0

我的問題:我想知道爲什麼來自預準備語句的查詢結果應該每次運行不一致。行返回不一致

警告奇怪的東西在前面。

我在Oracle數據庫中。我正在使用ojdbc6.jar驅動程序。我有一個查詢返回大約1300行(它隨時間而變化,因爲where子句取決於sysdate)。當我在Toad(SQL Developer工具)和Netbeans Services工具(與數據庫的另一個接口)中運行它時,它工作得很好。我的結果是一致的。但是當我在java代碼中運行查詢時,結果高度不一致。爲了嘗試查看每個結果計數返回的頻繁程度,我將其放入for循環並迭代了10次。在每次運行中有一個相對一致的行數,但不在運行中。我的輸出和代碼如下。讓我知道是否有更多的信息是有幫助的。

當試圖作品(八九不離十...):

Got real queries (1308) 
Got real queries (1308) 
Got real queries (1308) 
Got real queries (1307) 
Got real queries (1307) 
Got real queries (1317) 
Got real queries (1317) 
Got real queries (1317) 
Got real queries (1317) 
Got real queries (1315) 

當嘗試不起作用:

Got real queries (212) 
Got real queries (212) 
Got real queries (212) 
Got real queries (212) 
Got real queries (212) 
Got real queries (212) 
Got real queries (212) 
Got real queries (212) 
Got real queries (212) 
Got real queries (212) 

我的代碼:

public static void main(String[] args) throws Exception { 
    for (int i = 0; i < 10; i++) { 
    List<String> realQueries = new ArrayList<>(); 
    String sqlAllRealQueries = "select V.SQL_FULLTEXT" + StringHelper.newline 
      + "from v$sql v" + StringHelper.newline 
      + "where V.PARSING_SCHEMA_NAME = 'DSS1_PTC'" + StringHelper.newline 
      + "and to_number(replace(replace(replace(v.last_load_time,'-',''), '/',''), ':','')) > to_number(to_char(sysdate - (24/24),'yyyymmddHH24mmss'))" + StringHelper.newline 
      + "order by V.LAST_LOAD_TIME desc"; 
    try (ResultSet rs = getInstance().executeQuery(sqlAllRealQueries)) { 
     while (rs.next()) { 
     realQueries.add(rs.getString(1)); 
     } 
    } 

    System.out.println("Got real queries (" + realQueries.size() + ")"); 
    } 
    System.exit(0); 
} 

public ResultSet executeQuery(String connection, String query, QueryParameter... params) throws DataException, SQLException { 
    Connection conn = ConnectionPool.getInstance().get(connection); 
    PreparedStatement pstmt = conn.prepareStatement(query); 
    for (int i = 1; i <= params.length; i++) { 
    //... stuff to fill in the '?'s of the query (in this case, there are none). 
    } 
    } 

    ResultSet rs = pstmt.executeQuery(); 
    ConnectionPool.getInstance().release(conn); 
    return rs; 
} 
+0

除非您確實需要使用JDBC運行,否則使用過程或函數可能會更好。 –

+0

@PaulVargas是的,我認爲你是對的。我現在給它一個鏡頭... – kentcdodds

回答

0

你有小bug日期格式'yyyymmddHH24mmss',應該是'yyyymmddHH24miss'(「mi」而不是「mm」) mm表示月,m英寸是「mi」。

+0

噢哇...多麼尷尬...不幸的是,改變它後,我仍然遇到同樣的問題,所以這不是問題...我會給你無論如何,接受。我決定走一條完全不同的路線。感謝您的提示,但! – kentcdodds