Java - SQLite Web Service Returning Blob

2019-01-20 06:11发布

问题:

I have a Java web service that is querying a SQLite database that contains blob data. I'm returning sql statements so that consumers of the service can just insert/update/delete with out processing the data. My problem is when I get to the blob data, the sqlite-jdbc driver says that the getBlob function is not implemented. So my question is this doable? Is there a better driver or way to accomplish this task?

Thanks!

回答1:

SQLite supports BLOB datatype. Sqlitejdbc driver does not support the ResultSet#getBlob() method but BLOBs are supported. Just use ResultSet#getBytes() method. Here is the sample code (I did not put proper exception handling in this code to make it simple):

package test;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Arrays;

public class SQLiteTest {

public static void main(String[] args) throws SQLException,
        ClassNotFoundException {
    Class.forName("org.sqlite.JDBC");
    Connection connection = DriverManager
            .getConnection("jdbc:sqlite:test.db");
    Statement statement = connection.createStatement();
    createTable(statement);
    insertBlob(connection);
    byte[] bytes = query(statement);
    System.out.println(Arrays.toString(bytes));
            statement.close();
    connection.close();
}

private static void createTable(Statement statement) throws SQLException {
    statement.execute("CREATE TABLE test (data BLOB)");
}

private static void insertBlob(Connection connection) throws SQLException {
    PreparedStatement pStatement = connection
            .prepareStatement("INSERT INTO test VALUES (?)");
    pStatement.setBytes(1, new byte[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 });
    pStatement.execute();
    pStatement.close();
}

private static byte[] query(Statement statement) throws SQLException {
    ResultSet rs = statement.executeQuery("SELECT data FROM test");
    byte[] bytes = rs.getBytes(1);
    return bytes;
}

}