java向sqlite插入blob格式图片

本文提供了一个使用Java操作SQLite数据库的示例代码,演示了如何创建表并插入包含大型二进制对象(BLOB)的数据。具体步骤包括加载SQLite JDBC驱动、创建数据库连接、创建表、读取文件为字节数组并插入到数据库中。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

    public static void main(String[] args) {
        byte[] b=null;
        Connection conn=null;

        Statement stmt;
        try {
            Class.forName("org.sqlite.JDBC");
            conn = DriverManager.getConnection("jdbc:sqlite:test.db?journal_mode=DELETE&synchronous=OFF");
            System.out.println("Opened database successfully");
            stmt = conn.createStatement();
            String sql = "CREATE TABLE IF NOT EXISTS  COMPANY (ID BLOB);";
            stmt.executeUpdate(sql);
            InputStream inputStream = new FileInputStream(new File("C:\\Program Files\\feiq\\Recv Files\\wms (1).tiff"));
            ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
            int ch;
            conn.setAutoCommit(false);//关闭自动提交,可以实现多次添加数据,一次提交,提高效率(对于插入一条数据可以不关上此功能)
            while ((ch = inputStream.read()) != -1) {
                byteArrayOutputStream.write(ch);
            }
            b= byteArrayOutputStream.toByteArray();
            byteArrayOutputStream.close();

        }catch (Exception e){
            System.out.println("file error");
        }
        try {
            ByteArrayInputStream c = new ByteArrayInputStream(b);
            PreparedStatement pstmt = null;
            String sql="insert into COMPANY values (?)";
            pstmt = conn.prepareStatement(sql);
            pstmt.setBinaryStream(1, c, c.available());
            pstmt.executeUpdate();
            conn.commit();
        }catch (Exception e){
            System.out.println(e);
        }


    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值