2014-02-24 98 views
0

我使用的SQLite Xerials JDBC驅動程序和想做的事你能想象的最簡單的事情:下表JDBC PreparedStatement.setString()與SQLite無法正常工作?

我已經創建:

CREATE TABLE IF NOT EXISTS households (hostname_id_pk INTEGER PRIMARY KEY, hostname TEXT UNIQUE, vm TEXT); 

現在,我想有一個參數化插入statment我用PreparedStatment如下:

public static void main(String[] args) throws ClassNotFoundException { 
    Class.forName("org.sqlite.JDBC"); 
    Connection con = null; 
    PreparedStatement updateHouseholdStmt = null; 

    try { 
     con = DriverManager.getConnection(DB_IDENTIFIER);   

     String getHouseholdString = "SELECT hostname_id_pk FROM households WHERE hostname = ?"; 
     String updateHouseholdString = "INSERT INTO households (hostname, vm) values(?, 'VM1')"; 

     getHouseholdStmt = con.prepareStatement(getHouseholdString); 
     getHouseholdStmt.setString(1, "test1"); 

     updateHouseholdStmt = con.prepareStatement(updateHouseholdString); 
     getHouseholdStmt.setString(1, "test1"); 

     ResultSet hhRS = getHouseholdStmt.executeQuery(); 
     int hhId = -1; 

     if(hhRS.next()){ 
      hhId = hhRS.getInt(1); 
      System.out.println(hhId); 
     } else { 
      System.out.println(updateHouseholdStmt.executeUpdate()); 
     } 

    } catch (SQLException e) { 
     System.err.println(e.getMessage()); 
    } finally { 
     try { 
      if (con != null) { 
       con.close(); 
      } 
      if (getHouseholdStmt != null){ 
       getHouseholdStmt.close(); 
      } 
      if (updateHouseholdStmt != null) { 
       updateHouseholdStmt.close(); 
      } 
     } catch (SQLException e) { 
      System.err.println(e); 
     } 
    } 

} 

在這種情況下,我可以在數據庫中找到的唯一一件事就是帶着(1, , VM1)這意味着條目創建新條目,但該字符串參數丟失,出於某種原因。

當我更換「?」在帶有示例值的updateHousholdStatement()中,並刪除.setString(...)方法行,一切正常。

我錯過了什麼?我今天早上已經檢查過這一千次了。

Thx提前。

+0

dddaaarn ...好吧謝謝你們:)這是當你起牀在牀上的錯誤的一面。 –

回答

2

請更正以下行:

updateHouseholdStmt = con.prepareStatement(updateHouseholdString); 
getHouseholdStmt.setString(1, "test1"); 

updateHouseholdStmt = con.prepareStatement(updateHouseholdString); 
updateHouseholdStmt.setString(1, "test1"); 
2

當更新,你設置並執行了錯誤的變量:

getHouseholdStmt = con.prepareStatement(getHouseholdString); 
getHouseholdStmt.setString(1, "test1"); 

updateHouseholdStmt = con.prepareStatement(updateHouseholdString); 
getHouseholdStmt.setString(1, "test1"); //updating the select query 
ResultSet hhRS = getHouseholdStmt.executeQuery(); //you're executing the select query again! 

它應該是:

getHouseholdStmt = con.prepareStatement(getHouseholdString); 
getHouseholdStmt.setString(1, "test1"); 

updateHouseholdStmt = con.prepareStatement(updateHouseholdString); 
updateHouseholdStmt .setString(1, "test1"); //update stmt 
ResultSet hhRS = updateHouseholdStmt .executeQuery(); //update stmt 
0

首先,getHouseholdStmt語句未聲明爲PreparedStatement。第二,你需要executeUpdate()你的PreparedStatement updateHouseholdStmt(updateHouseholdStatement.executeUpdate();)