插入操作(删除和更改操作类似)
在进行对数据库的插入操作之前,我们需要一个图片粘贴至当前project的文件下,这样来我们就可以使用该图片的相对路径来书写,当然也可以使用绝对路径。
由于Blob类型的字段本身的特性,不适合使用常规的类来接收它,因此我们选择使用流的方式来插入字段,其他就大差不差了,以下是代码:
//向数据表插入Blob类型的字段
@Test
public void testInsert() throws Exception {
Connection conn = jdbcutils.getConnection();
String sql="insert into customers(name,email,birth,photo) values(?,?,?,?)";
PreparedStatement ps = conn.prepareStatement(sql);
ps.setObject(1,"saber");
ps.setObject(2, "saber@s.com");
ps.setObject(3, "2000-01-01");
FileInputStream is = new FileInputStream("图片名.jpg");
ps.setBlob(4, is);
ps.execute();
}
查询操作
前段部分的代码跟之前的代码类似,到接收Blob字段的时候我们选择使用InputStream,然后使用FileOutputStream来存为本地文件,是Java中文件方面的操作。
public void testQuery(){
Connection conn=null;
PreparedStatement ps=null;
ResultSet rs=null;
InputStream is=null;
FileOutputStream fos=null;
try {
conn = jdbcutils.getConnection();
String sql="select id,name,birth,email,photo from customers where id=?";
ps = conn.prepareStatement(sql);
ps.setObject(1, 22);
rs = ps.executeQuery();
if(rs.next()) {
int id=rs.getInt("id");
String name=rs.getString("name");
String email=rs.getString("email");
Date birth=rs.getDate("birth");
Customer cust=new Customer(id,name,email,birth);
System.out.println(cust);
Blob photo = rs.getBlob("photo");
is = photo.getBinaryStream();
fos=new FileOutputStream("自定义文件名.jpg");
byte[]buffer=new byte[1024];
int len;
while((len=is.read(buffer))!=-1) {
fos.write(buffer,0,len);
}
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally {
try {
if(is!=null)
is.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
if(fos!=null)
fos.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
jdbcutils.closeResource(conn, ps,rs);
}
当然在调用jdbcutils中的关闭方法之余也不要忘记关闭文件输入输出流。