2014-02-14 85 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