java向sqlite插入blob格式图片

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


    }

你可能感兴趣的:(水贴)