2011-05-31 70 views
2

我已經使用SQLite創建了一個數據庫。我想更新「功能」列(類型Blob)的值...但我不知道如何編寫「更新」語句。 這是我的嘗試:SQLite中更新語句的問題

try { 
     stat = conn.createStatement(); 
    } catch (SQLException e) { 
    } 
    try { 
     byte[] b = getFunction(); 
     stat.executeUpdate("update table set features="+b); 
    } catch (SQLException e) { 
    } 

我得到的follwing錯誤:

java.sql.SQLException: unrecognized token: "[[email protected]" 

所以我想這 「B」 是什麼問題?

回答

3

試試這個用的PreparedStatement:

Connection con = null; 
PreparedStatement stmt = null; 

try { 
    byte[] b = getFunction(); 
    con = ...; 
    stmt = con.prepareStatement("update table set features=?"); 
    stmt.setBytes(1, b); 
    stmt.executeUpdate(); 

    con.commit(); 
} 
catch (SQLException e) { 
    //handle exception (consider con.rollback()) and con maybe null here) 
} 
finally { 
    //close stmt and at least con here (all maybe null here) 
} 

個人我一直使用的PreparedStatement。當你必須編寫大量的代碼時,請考慮編寫一些實用程序類以減少Boilerplate-Code。

特別是在處理普通JDBC時,您應該考慮在連接,語句和ResultSet方法上編寫Utilty-Classes以調用null-safe調用方法。

編輯 托馬斯榮格寫了關於防止SQL注入是另一個總是使用PreparedStatements的大親。 +1爲他:-)

+0

它的工作原理:)...非常感謝你 – Mara 2011-05-31 15:43:44

-1
stat.executeUpdate("update table set features="+b[0].toString()); 

必須使用+

+0

對不起,拼寫錯誤,我用「+」 – Mara 2011-05-31 15:09:45

+0

你也設置了數組試試b [0] – John 2011-05-31 15:11:00

+0

不行。 'byte []。toString()'不返回SQLite期望的'X'...''格式。 – dan04 2011-05-31 23:49:18

5

[B @ 13a317a看起來像(在此情況下b.toString())一個陣列,以字符串結果。你應該使用一個準備好的語句,如:

update table set features=? 

一個例子是here

通常,您不應該通過連接字符串來創建SQL。這是SQL注入問題的祕訣。

+0

+1:我們有一個贏家。正確答案。 – 2011-05-31 15:22:45

+0

感謝例子 – Mara 2011-05-31 15:51:58