您的位置:首页 > 数据库

jdbc保存图片到数据库并读取代码

2014-05-15 22:22 351 查看
import java.io.FileInputStream;

import java.io.FileOutputStream;

import java.io.InputStream;

import java.io.OutputStream;

import oracle.sql.BLOB;

import java.sql.Connection;

import java.sql.PreparedStatement;

import java.sql.ResultSet;

import util.DBConnection;

import base.dao.BaseDAO;

public class ImgDAOImpl extends BaseDAO implements ImgDAO {

Connection con;
ResultSet rs;
PreparedStatement pre;
BLOB img;//oracle.sql.BLOB类 不能用java.sql.Blob 操纵clob也同理
boolean isSuccess;

public void save() throws Exception {

con = DBConnection.getDBConnection().getConnection();
con.setAutoCommit(false);

pre = con.prepareStatement("insert into fw.img values (?,empty_blob())");
pre.setInt(1, 1);
if(pre.executeUpdate()>0)
{

pre = con.prepareStatement("select i_img from fw.img where i_id=? for update");
pre.setInt(1, 1);
rs = pre.executeQuery();
if(rs.next())
{
img = (BLOB) rs.getBlob("i_img");//获得blob字段

InputStream is = new FileInputStream("src/1.jpg");
byte[] bt = new byte[is.available()];
is.read(bt);

OutputStream os = img.getBinaryOutputStream();
os.write(bt);
os.flush();
is.close();
os.close();
isSuccess=true;
}
if(isSuccess)
{
con.commit();
System.out.println("插入完毕");

}
else
{
con.rollback();
}
}
else
{
con.rollback();
}
DBConnection.getDBConnection().closeConnection(rs, pre, con);

}

public void read() throws Exception{
con = DBConnection.getDBConnection().getConnection();
pre = con.prepareStatement("select i_img from fw.img where i_id=? and i_img is not null");
pre.setInt(1, 1);
rs = pre.executeQuery();
if(rs.next())
{
  img = (BLOB) rs.getBlob("i_img");//获得blob字段
  byte[] bt = img.getBytes(1, (int) img.length());//获得blob字段的内容保存到数组bt中
 
  OutputStream os = new FileOutputStream("src/2.jpg");
  os.write(bt);
  os.flush();
  os.close();
  System.out.println("读取成功,读出来的图片在src下 2.jpg");
}
DBConnection.getDBConnection().closeConnection(rs, pre, con);
}

public static void main(String[] args) throws Exception {
ImgDAO dao = new ImgDAOImpl();
dao.save();
dao.read();
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐