假設你需要從選擇創建一個新的表,那麼你就應該使用這個查詢:
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#execute
或PreparedStatement#executeUpdate
:
//the former query is a DDL query
pstmt.execute();
//the latter query is a DML query
pstmt.executeUpdate();
您不能通過JDBC參數化列_names_,僅_values_。 –
@MickMnemonic我在發佈答案之前測試了代碼。 –
好吧,看來你可以在'SELECT'中爲'INSERT'做到這一點,然後。對此功能的支持可能是供應商特定的? –