problems with update statement in SQLite

放肆的年华 提交于 2020-01-15 03:45:11

问题


I have created a database using SQLite. I want to update the value of a "features" column( type Blob)...but i do not know how to write the "update" statement . This is what i tried:

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

i get the follwing error :

java.sql.SQLException: unrecognized token: "[B@13a317a"

so i guess that "b" is the problem ?


回答1:


Try this one with 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)
}

Personally I am always using PreparedStatements. When you have to write a lot of this code then consider writing some Utility-Classes to reduce Boilerplate-Code.

In particular you should consider writing Utilty-Classes for null-safe calling methods on Connection, Statement and ResultSet methods when you are dealing with plain JDBC.

EDIT What Thomas Jung wrote about preventing SQL Injections is another big pro for always using PreparedStatements. +1 for him :-)




回答2:


[B@13a317a looks like a array to string result (b.toString() in this case). You should use a prepared statement for the blob like:

update table set features=?

An example is here.

Generally, you should never create a SQL by concatenating strings. This is the recipe for SQL injection problems.




回答3:


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

you have to use +



来源:https://stackoverflow.com/questions/6189637/problems-with-update-statement-in-sqlite

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!