2014-02-14 83 views
0

String qLink =「」;Java - Mysql - Multiple query

     qLink = "INSERT INTO trackgps.queclinklogs(Supplier,NtwProtocol,IMEI,log,DBTIME)" + 
           "VALUES"     + 
           "("       + 
           "'" + supplier    + "',"+ 
           "'" + protocol    + "',"+ 
           "'" + failedQIMEI   + "',"+ 
           "'" + failedQLog   + "',"+ 
           "'" + currentQuecTimestamp + "'" + 
           "),"      + 
           "("       + 
           "'" + supplier    + "'" + "," + 
           "'" + protocol    + "'" + "," + 
           "'" + QuecLinkIMEI   + "'" + "," + 
           "'" + data2     + "'" + "," + 
           "'" + currentQuecTimestamp + "'" + 
           ")";  


         Statement stmtLink = connQ.createStatement(); 
         stmtLink.execute(qLink); 
         stmtLink.close(); 

String bytesconsumption =「」;

    bytesconsumption = "INSERT INTO test_backoffice.carrierDataConsumption(IMEI,beginMonth,endMonth,dataConsumed,month,year) VALUES" + 
             "("                            + 
             "'"+ QuecLinkIMEI                     + "'" + "," + 
             "NOW()"                         + "," + 
             "NOW()"                         + "," + 
             "'"+ totalBytesConsumed                     + "'," + 
             "MONTH(NOW())"                       + "," + 
             "YEAR(NOW())"                         + 
             ") ON DUPLICATE KEY UPDATE endMonth = NOW(), dataConsumed = dataConsumed + " + totalBytesConsumed; 

        Statement stmtbytesconsumption; 

        stmtbytesconsumption = connQ.createStatement(); 
        stmtbytesconsumption.execute(bytesconsumption); 
        stmtbytesconsumption.close(); 

String qdebug =「」;

qdebug = "INSERT INTO trackgps.rawdata(Module,SubModule,IMEI,listenerTime,msg)" + 
      "VALUES"     + 
      "("       + 
      "'"+ "LISTENER TCP"   + "'" + "," + 
      "'"+ SubMod     + "'" + "," + 
      "'"+ identifier    + "'" + "," + 
      "'"+ listendatetime   + "'" + "," + 
      "'"+ msg     + "'" + 
      ")";  

    Statement stmtqdebug = conn.createStatement(); 
    stmtqdebug.execute(qdebug); 
    stmtqdebug.close(); 

有沒有辦法在一個Java語句中執行這三個插入? 而不是創建3個3個執行和3個關閉的語句?

我有其他問題,我應該使用語句還是PrepareStatements?

回答

1

可以調用所有3個查詢的一個聲明:

Statement stmt = conn.createStatement(); 
stmt.executeUpdate(qLink); 
stmt.executeUpdate(bytesconsumption); 
stmt.executeUpdate(qdebug); 
stmt.close(); 

使用PreparedSatement,而不是Statement當你想:

  • 有不同的參數
  • 執行相同的語句多次不採取有關參數格式化,如護理。如果listendatetime是Timestamp類型,則只能使用ps.setTimestamp(4, listendatetime),並且驅動程序會在底層數據庫中正確地獨立格式化它。
1

可以將查詢連接到「;」字符來分割它並以獨特的語句執行所有操作。

查詢:

"INSERT INTO table1 ... ;INSERT INTO table2 ...;" 

和執行:

Statement st = conn.createStatement(); 
st.execute("INSERT INTO table1 ... ;INSERT INTO table2 ...;"); 
st.close(); 

乾杯

+1

tks :)。我要去嘗試一下。 – ThelmaJay

+0

告訴我,如果作品! :) – 2014-02-14 15:27:00

+0

它不起作用:(它只適用於我單獨準備好的聲明。 – ThelmaJay