public void
insertByte(){
Connection conn=null;
PreparedStatement st=null;
ResultSet rs=null;
try{
conn=JdbcUtils.getconnection();
String sql="insert into
testblob(id,image) values(?,?)";
st=conn.prepareStatement(sql);
st.setString(1, "1");
File file=new File("src/1.jpg");
FileInputStream in=new FileInputStream(file);
st.setBinaryStream(2, in, (int)file.length());
int num=st.executeUpdate();
if(num!=0){
System.out.println("插入成功");
}
}catch(Exception e){
throw new RuntimeException(e);
}finally{
JdbcUtils.release(conn, st, rs);
}
}
@Test
public void
readByte() throws SQLException, IOException{
Connection conn=null;
PreparedStatement st=null;
ResultSet rs=null;
try{
conn=JdbcUtils.getconnection();
String sql="select image from testblob where id=?";
st=conn.prepareStatement(sql);
st.setString(1, "1");
rs=st.executeQuery();
if(rs.next()){
InputStream in=rs.getBinaryStream("image");
OutputStream out=new FileOutputStream("c:\\1.jpg");
//注意"c:\\1.jpg"写法
try{
int len=0;
byte buffer[]=new byte[1024];
while((len=in.read(buffer))>0){
out.write(buffer, 0, len);
}
}finally{
if(in!=null){
try{
in.close();
}catch(Exception e){
throw new RuntimeException(e);
}
}
if(out!=null){
try{
in.close();
}catch(Exception e){
throw new RuntimeException(e);
}
}
}
}
}finally{
JdbcUtils.release(conn, st, rs);
}
}