標籤:
1.資料庫表結構如下
這裡資料類型根據插入資料的大小進行選擇。
1.具體實現如下,這裡主要將圖片轉為二進位存入資料庫
1 Connection conn=null; 2 PreparedStatement st=null; 3 String sql="insert into users(username,password,regdate,img) values(?,?,?,?)"; 4 try { 5 if(conn==null){ 6 conn = db.getConnection(); 7 } 8 st = conn.prepareStatement(sql); 9 File file=new File(this.getClass().getClassLoader().getResource("../../").getPath()+"1.jpeg");10 InputStream input=new BufferedInputStream(new FileInputStream(file));11 st.setString(1,user.getUsername());12 st.setString(2, user.getPassword());13 st.setDate(3, new Date(user.getRegdate().getTime()));14 st.setBinaryStream(4, input,(int)file.length());//這裡需要注意,後面的file.length()資料類型為long,在這裡需要將其強轉為int類型15 int result=st.executeUpdate(); 16 if(result>0){17 return true;18 }19 } catch (SQLException e) {20 e.printStackTrace();21 } catch (FileNotFoundException e) {22 e.printStackTrace();23 } finally{24 if(st!=null)25 db.close(st);26 if(conn!=null)27 db.close(conn);28 }29 return false;
3.注意:
PreparedStatement對象中的setBinaryStream(int index,inputstream input,long)方法在jdk1.6存在,但是在mysql的jdbc中並沒有實現,如果後面的檔案長度沒有轉換為int的話則會報以下錯誤
java.lang.AbstractMethodError: com.mysql.jdbc.PreparedStatement.setBinaryStream(ILjava/io/InputStream;J)V
4.從資料庫中取出二進位檔案
1 Connection conn = null; 2 PreparedStatement st = null; 3 String sql = "select * from users where id=?"; 4 try { 5 if (conn == null) { 6 conn = JdbcUtil.getConnection(); 7 } 8 st = conn.prepareStatement(sql); 9 st.setInt(1, user.getId());10 File file = new File(this.getClass().getClassLoader().getResource("../../").getPath()+ "back.jpeg");11 OutputStream output = new BufferedOutputStream(new FileOutputStream(file));12 ResultSet result = st.executeQuery();13 while (result.next()) {14 byte[] by = new byte[1024];15 int i = 0;16 InputStream input = result.getBinaryStream(5);//取出位元據 17 try {18 while ((i = input.read(by)) != -1)19 output.write(by, 0, i);//通過輸出資料流寫到檔案中 20 } catch (IOException e) {21 e.printStackTrace();22 }23 24 }25 26 } catch (SQLException e) {27 e.printStackTrace();28 } catch (FileNotFoundException e) {29 e.printStackTrace();30 } finally {31 if (st != null)32 JdbcUtil.close(st);33 if (conn != null)34 JdbcUtil.close(conn);35 }36 return false;
java之操作MySql操作大對象