java向sqlite插入blob格式图片

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/love_QJP/article/details/81450350
    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);
        }


    }
展开阅读全文

没有更多推荐了,返回首页