我有以下代碼片段。我刪除了更多細節。我有一個for循環與其中的所有數據。我運行for循環for(int i = 0; i < list.getLength(); i ++)。會發生什麼情況是,當任何一個數據導致錯誤的sql說數據有一個斜槓等,然後它會導致異常和for循環的其餘部分不能繼續。我怎麼能跳過那個例外,繼續休息?忽略異常並繼續插入其餘的數據
這是一段代碼。
Connection dbconn = null;
Statement stmt1 = null;
Statement stmt2 = null;
try
{
dbconn = DriverManager.getConnection("jdbc:mysql://localhost:3306/test1", "tes1", "te15");
stmt1 = dbconn.createStatement();
stmt2 = dbconn.createStatement();
DateFormat outDf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date date = Calendar.getInstance().getTime();
String value = null;
for (int i = 0; i < list.getLength(); i++)
{
String insertCommand = "INSERT INTO command SET .........";
System.out.println("\n SET INSERT :" + insertCommand);
int count = stmt1.executeUpdate(insertCommand);
}
}
catch (SQLException ex)
{
System.out.println("MyError Error SQL Exception : " + ex.toString());
}
catch (Exception rollback)
{
System.out.println("\nRollback :");
rollback.printStackTrace(System.out);
}
catch (Exception e)
{
System.out.println("\n Error here :");
e.printStackTrace(System.out);
}
finally
{
try
{
if (stmt1 != null)
{
stmt1.close();
}
}
catch (SQLException ex)
{
System.out.println("MyError: SQLException has been caught for stmt1 close");
ex.printStackTrace(System.out);
}
try
{
if (stmt2 != null)
{
stmt2.close();
}
}
catch (SQLException ex)
{
System.out.println("MyError: SQLException has been caught for stmt2 close");
ex.printStackTrace(System.out);
}
try
{
if (dbconn != null)
{
dbconn.close();
}
else
{
System.out.println("MyError: dbConn is null in finally close");
}
}
catch (SQLException ex)
{
System.out.println("MyError: SQLException has been caught for dbConn close");
ex.printStackTrace();
}
}
怎麼樣'INSERT忽略...作爲一個測試。那麼它真正解決了真正的問題?我不確定*忽略*實際上是否會倖免於例外部分。 – Drew
如果因爲數據導致sql語法錯誤而出現異常,那麼您可能容易受到[sql注入攻擊](http://bobby-tables.com) –
是的,我瞭解該漏洞,但我沒有選擇但是要忽略那個例外,繼續剩下的事情? – user5313398