Java - Mysql - 多重查询 [英] Java - Mysql - Multiple query
本文介绍了Java - Mysql - 多重查询的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
String qLink = "";
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 = "";
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 = "";
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 个关闭?
Is there anyway to execute this three inserts in just one java statement? Instead of creating 3 Statements with 3 executes and 3 closes?
我还有其他问题,我应该使用 Statements 还是 PrepareStatements?
Other question I have, Should I use Statements or PrepareStatements?
推荐答案
您可以在一个语句上调用所有 3 个查询:
You can call all 3 queries on one statement:
Statement stmt = conn.createStatement();
stmt.executeUpdate(qLink);
stmt.executeUpdate(bytesconsumption);
stmt.executeUpdate(qdebug);
stmt.close();
在需要时使用 PreparedSatement
而不是 Statement
:
Use PreparedSatement
instead of Statement
when you want:
- 使用不同的参数集多次执行相同的语句
- 不要关心参数格式,例如.如果
listendatetime
是 Timestamp 类型,您可以只使用ps.setTimestamp(4, listendatetime)
和驱动程序在底层数据库上独立正确格式化它.
- to execute the same statement many times with different set of parameters
- don't take care about parameter formating, eg. if
listendatetime
is of type Timestamp, you can use justps.setTimestamp(4, listendatetime)
and a driver formats it properly independently on underlaying database.
这篇关于Java - Mysql - 多重查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文