2012-02-15 54 views
1

可能重複:
Getting java.sql.SQLException: Operation not allowed after ResultSet closedJDBC異常:操作的ResultSet後不允許關閉

我工作的一些代碼拋出Operation not allowed after ResultSet closed例外。這裏是:

ResultSet res = stmt.executeQuery("SELECT codigo FROM projecto WHERE nome='" 
    + auxiliarNomes.elementAt(i).toString() + "'"); 
while (res.next()) { 
    codigo = res.getString("codigo"); 
    stmt.executeUpdate("insert into categoriaprojectos values(" 
     + "'" + codigo + "'" + "," + "'" + Antena.RetornaCodigoProjecto() + "')"); 
} 

我在做什麼錯了?

+1

搜索「SQL注入」,並找出爲什麼你的SQL建設是錯 – gbn 2012-02-15 10:39:16

回答

6

這是可能的。只需使用額外的連接和聲明。

Statement statementOne = connectionOne.createStatement(); 
Statement statementTwo = connectionTwo.createStatement(); 
ResultSet resultSetOne = statementOne.executeQuery("select * from x"); 

while (resultSetOne.next()) { 
    ResultSet resultSetTwo = statementTwo.executeQuery(String.format("select * from y where xy = %s", resultSetOne.getString(0))); 

    while (resultSetTwo.next()) { 
     String result = resultSetTwo.getString(0); 
    } 
} 
+0

Ofcourse一個的executeUpdate也可能而不是第二個查詢 – 2012-06-01 20:01:46

3

你的代碼是很髒寫,你應該使用PreparedStatementsparametrized SQL statements,因爲沒有他們有SQL注入的危險性大。這種方法更快,更清潔,更安全! 閱讀this

對於您的代碼,嘗試這樣做,您應該使用batch來插入多個操作。

String SEL_QUERY = "SELECT codigo FROM projecto WHERE nome= ?"; 
String UPDATE_QUERY = "INSERT INTO categoriaprojectos values(?)"; 

PreparedStatement ps,ps1 = null; 
ResultSet rs = null; 

ps = con.prepareStatement(SEL_QUERY); 
ps.setYourType(<data>); 
rs =stmt.executeQuery(); 
ps1 = con.prepareStatement(UPDATE_QUERY); 
while(rs.next()) 
{ 
    ps1.setYourType(rs.getType()); 
    ps1.addBatch(); 
} 
ps1.executeBatch(); 

您應該爲此使用批處理。它更快,更安全,更清潔。方法addBatch()將一組參數添加到您的PreparedStatement對象的一批命令中。 您將例如在批4個插件,然後將執行他們mass.This技術被命名爲數據聚類

相關問題