mySQL嵌套循环不会执行
我正在开发一个基于 SOAP 的 Web 服务,其中一部分我必须使用嵌套循环对数据库执行一些查询,问题是内部循环在放弃之前只执行一次。这是代码:
for(int i=0; i<selec.length; i++){
for(int j=0; j<sintom.length;j++){
var[(i*sintom.length)+j] = "INSERT INTO malattia (nome, eta, descrizione, sesso, etnia, sintomi) "
+ "VALUES ('" + malattia + "','" + eta + "','" + descrizione + "','" + sexarra[0] + "','" + selec[i] + "','" + sintom[j] + "')";
}
}
这是应该执行查询的地方:
if (errore.equals("")) {
try {
Statement st = conn.createStatement();
for(int i=0; i<selec.length; i++){
for(int j=0;j<sintom.length;j++){
st.executeUpdate(var[(i*sintom.length)+j]);}}
发生的情况是,无论 select 的大小如何,只要 sintom 的长度为 1,它都会正常工作,大于 1 就不起作用。
感谢您的专家建议,始终不胜感激!
I'm working on a SOAP based webservice where in a part of it i have to perform some queries on the database using nested loop, the problem is that the inner loop just gets executed for ONE time only, before giving up.This is the code:
for(int i=0; i<selec.length; i++){
for(int j=0; j<sintom.length;j++){
var[(i*sintom.length)+j] = "INSERT INTO malattia (nome, eta, descrizione, sesso, etnia, sintomi) "
+ "VALUES ('" + malattia + "','" + eta + "','" + descrizione + "','" + sexarra[0] + "','" + selec[i] + "','" + sintom[j] + "')";
}
}
This is where the queries are supposed to get executed:
if (errore.equals("")) {
try {
Statement st = conn.createStatement();
for(int i=0; i<selec.length; i++){
for(int j=0;j<sintom.length;j++){
st.executeUpdate(var[(i*sintom.length)+j]);}}
What happens is that no matter the size of select it will work fine as long as the length of sintom is 1,bigger than 1 and it wont work.
Thanks for your expert advices, always appreciated!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您的用例是应该使用准备好的语句的完美示例。在JDBC 教程中了解有关它们的更多信息。
使用准备好的语句可以避免
所以,代码应该是这样的:
Your use-case is a perfect example of a case where a prepared statement should be used. Read more about them in the JDBC tutorial.
Using a prepared statement would allow
So, the code should look like this:
尝试使用PreparedStatement及其Batch功能而不是普通查询来简化代码并防止SQL注入。
Try to use PreparedStatement and its Batch capability instead of plain query to simplify code and prevent SQL-injection.