2013-06-19 60 views
-2

我想連接到一個數據庫,並使用Java程序中的預準備語句更新其中的一個表 - 數據庫被稱爲「數據庫」,並在那裏有另一個名爲Views的文件夾我試圖更新的表(「TABLE」)是。這裏是我的代碼:在java中準備SQL語句

public void updateTable(Map<String, String> mp) throws SQLException { 

    String URL = "jdbc:oracle:thin:@localhost:1500:orcl"; 
    String USER = "user"; 
    String PASS = "password"; 
    Connection con = DriverManager.getConnection(URL, USER, PASS); 

    PreparedStatement updateTableName = null; 


    String updateString = 
     "update database.Views.TABLE " + 
     "set TABLENAME = ? " + 
     "where TABLENAME = ?"; 

    try { 
     con.setAutoCommit(false); 
     updateTableName = con.prepareStatement(updateString); 

     for (Map.Entry<String, String> e : mp.entrySet()) 
     { 
      updateTableName.setString(1, e.getValue()); 
      updateTableName.setString(2, e.getKey()); 
      updateTableName.executeUpdate(); 
      con.commit(); 

     } 

    } catch (SQLException e) { 

     if (con != null) 
     { 
      try { 
       System.err.print("Transaction is being rolled back"); 
       con.rollback(); 
      } catch (SQLException excep) { 

      } 
     } 
    } finally { 
     if (updateTableName != null) 
     { 
      updateTableName.close(); 
     } 
     con.setAutoCommit(true); 
} 
    con.close(); 
} 

每當我運行代碼時,它顯示「正在回滾事務」。任何想法在try語句中有什麼錯誤?提前致謝!

編輯:當我改變它打印異常,它讀取ORA-00971:缺少SET關鍵字。

+4

而不是隻抓,印刷/記錄異常可能連鎖行業é一些線索 – kosa

+3

迪你讀過異常嗎? – SLaks

回答

0

好吧,我想通了,@Spiff我做了更改爲只更新TABLE1最簡單的查詢,但我還拿出了:

String updateString = 
    "update database.Views.TABLE " + 
    "set TABLENAME = ? " + 
    "where TABLENAME = ?"; 

,並將其與

合併成一條線
updateTableName = con.prepareStatement(updateString) 

做:

updateTableName = con.prepareStatement(update TABLE1 set TABLENAME = ? where TABLENAME = ?); 
+0

太棒了,很高興它的作品! – Spiff

6
"update database.Views.TABLE" + 
    "set TABLENAME = ?" + 
    "where TABLENAME = ?"; 

這個字符串的值是

update database.Views.TABLEset TABLENAME = ?where TABLENAME = ? 

這不是有效的SQL。

+0

我搞砸間距是啊,但是「database.Views.TABLE」無效? – user22

+0

@ user22您是否嘗試修復間距? – djechlin

+0

@djechlin是啊我修復了這個問題 – user22

0

您應該嘗試記錄您在第1個catch塊中捕獲的SQLException,這會給您清楚地指出問題所在。

在任何情況下,TABLE是一個SQL保留關鍵字,您不應該被允許爲這樣的表命名 - 至少嘗試將它重命名爲TABLE1,因爲缺乏更好的名稱。

+0

這個表在我的程序中是一個不同的名字我只是在這裏改變它,所以這不是問題。但是,當我登錄它說它是「缺少SET關鍵字」 – user22

+0

查詢現在是什麼樣子?它看起來像間距問題尚未解決。 – Spiff

+0

它現在用間距 – user22