2015-04-28 38 views
0

我目前正在嘗試在jdbc的preparedStaten中使用DECLARE子句。我寫的代碼是:如何在jdbc的語句中使用DECLARE子句?

  statement.executeUpdate(" declare @variable int set @variable = "+timer+" INSERT INTO table1 values (ip, protocol, counter, timer) SELECT ip,protocol,counter,@variable FROM table2 ORDER BY counter DESC LIMIT 5 OFFSET 0 ;"); 

我想要得到的是創建一個新的表(即表1),其中包括從表2的前5名(每5秒EG),以預定義間隔。間隔是計時器變量。計時器變量通過一個方法傳遞。

注意:我不知道使用preparedStatement是否有任何區別。我嘗試了兩個。

回答

1

假設你需要從選擇創建一個新的表,那麼你就應該使用這個查詢:

CREATE TABLE table1 SELECT ip,protocol,counter,@variable FROM table2 ORDER BY counter DESC LIMIT 5 OFFSET 0 

但是,如果你這樣做Java和使用PreparedStatement那麼你可以傳遞作爲@variable值一個參數,從而擺脫了以前的查詢。所以,你的查詢將看起來像這樣在Java代碼:

String sql = 
    "CREATE TABLE table1" 
    + " SELECT ip,protocol,counter,?" 
    + " FROM table2" 
    + " ORDER BY counter DESC" 
    + " LIMIT 5 OFFSET 0"; 

假設你已經擁有的表創建table1和你只是加入了最新的成果轉化爲從table2,那麼該查詢將是這樣的:

INSERT INTO table1 values (ip, protocol, counter, timer) SELECT ip,protocol,counter,@variable FROM table2 ORDER BY counter DESC LIMIT 5 OFFSET 0 

同樣,您可以傳遞值@variable作爲參數。查詢將看起來像這樣在Java代碼:

String sql = 
    "INSERT INTO table1 (ip, protocol, counter, timer)" 
    + " SELECT ip,protocol,counter,?" 
    + " FROM table2" 
    + " ORDER BY counter DESC" 
    + " LIMIT 5 OFFSET 0"; 

然後,你將準備這樣的查詢:

PreparedStatement pstmt = con.prepareStatement(sql); 
//setting your variable as the parameter in the query 
pstmt.setString(1, timer); 

最後,您將使用PreparedStatement#executePreparedStatement#executeUpdate

//the former query is a DDL query 
pstmt.execute(); 
//the latter query is a DML query 
pstmt.executeUpdate(); 
+0

您不能通過JDBC參數化列_names_,僅_values_。 –

+0

@MickMnemonic我在發佈答案之前測試了代碼。 –

+0

好吧,看來你可以在'SELECT'中爲'INSERT'做到這一點,然後。對此功能的支持可能是供應商特定的? –

相關問題