Java实现MySQL图片存取操作
转载自:http://blog.csdn.net/thc1987/article/details/3972201
存入操作
- /*
- ---------------表结构------------
- 表名:student2
- +--------+-------------+------+-----+---------+-------+
- | Field | Type | Null | Key | Default | Extra |
- +--------+-------------+------+-----+---------+-------+
- | id | int(4) | NO | PRI | NULL | |
- | name | varchar(20) | YES | | NULL | |
- | stupic | blob | YES | | NULL | |
- +--------+-------------+------+-----+---------+-------+
- */
- package com.ibm.jdbc;
- import java.io.*;
- import java.sql.*;
- public class StoreBLOB {
- public static void main(String[] args) {
- //连接MySQl数据库
- Connection con=DBManager.getConnection();
- PreparedStatement ps=null;
- InputStream in=null;
- try {
- //从本地硬盘读取一张读片
- in=new FileInputStream("d:/111.jpg");
- ps=con.prepareStatement("insert into student2 values(?,?,?)");
- ps.setInt(1,2);
- ps.setString(2, "Tom");
- ps.setBinaryStream(3, in, in.available());
- ps.executeUpdate();
- } catch (IOException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }catch (SQLException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- finally
- {
- try {
- //关闭流
- if(in!=null) in.close();
- } catch (IOException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- //关闭相关连接
- DBManager.close(ps, con);
- }
- }
- }
取出操作
- package com.ibm.jdbc;
- import java.sql.*;
- import java.io.*;
- public class GetBLOB {
- public static void main(String[] args) {
- Connection con=DBManager.getConnection();
- Statement st=null;
- ResultSet rs=null;
- InputStream in=null;
- OutputStream out=null;
- try {
- st=con.createStatement();
- rs=st.executeQuery("select stupic from student2 where id=2");
- rs.next(); //将光标指向第一行
- //从rs中读取stupic放进InputStream对象中
- in=rs.getBinaryStream("stupic");
- //申明byte数组,用来存放图片流
- byte[] b=new byte[40000];
- in.read(b); //从InputStream对象中读取数据放进byte数组中
- //实例化OutputStream对象,在D盘创建一个图片文件
- out=new FileOutputStream("d:/222.jpg");
- //将文件输出,内容则为byte数组里面的数据
- out.write(b);
- out.flush();
- } catch (SQLException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- catch (IOException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- finally
- {
- try {
- if(in!=null)
- in.close();
- if(out!=null)
- out.close();
- } catch (IOException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- DBManager.close(rs, st, con);//关闭相关连接
- }
- }
- }
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。