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