Reputation: 79
String qLink = "";
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();
Is there anyway to execute this three inserts in just one java statement? Instead of creating 3 Statements with 3 executes and 3 closes?
Other question I have, Should I use Statements or PrepareStatements?
Upvotes: 0
Views: 713
Reputation: 2189
You can call all 3 queries on one statement:
Statement stmt = conn.createStatement();
stmt.executeUpdate(qLink);
stmt.executeUpdate(bytesconsumption);
stmt.executeUpdate(qdebug);
stmt.close();
Use PreparedSatement
instead of Statement
when you want:
listendatetime
is of type Timestamp, you can use just ps.setTimestamp(4, listendatetime)
and a driver formats it properly independently on underlaying database.Upvotes: 1
Reputation:
You can concatenate the queries with a ";" character to split it and execute all in a unique statement.
The query:
"INSERT INTO table1 ... ;INSERT INTO table2 ...;"
and the execution:
Statement st = conn.createStatement();
st.execute("INSERT INTO table1 ... ;INSERT INTO table2 ...;");
st.close();
Cheers
Upvotes: 1