2011-05-31 58 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