Java - 返回Blob的SQLite Web服务

时间:2012-02-07 20:57:31

标签: java web-services sqlite blob

我有一个Java Web服务,它正在查询包含blob数据的SQLite数据库。我正在返回sql语句,以便服务的使用者只需插入/更新/删除而不处理数据。我的问题是当我得到blob数据时,sqlite-jdbc驱动程序说没有实现getBlob函数。所以我的问题是可行的吗?有没有更好的驱动程序或方法来完成这项任务?

谢谢!

1 个答案:

答案 0 :(得分:5)

SQLite支持BLOB数据类型。 Sqlitejdbc driver不支持ResultSet#getBlob()方法,但支持BLOB。只需使用ResultSet#getBytes()方法。下面是示例代码(我没有在此代码中进行适当的异常处理以使其变得简单):

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;
}

}