今天在做项目的时候遇到一个问题,将图片存储在数据库中,由于数据库中不能直接存储图片类型文件,所以只能转为二进制存储,具体实现如下:
数据库处理:
将字段类型设置为bolb类型
java处理:
public void tt1() {
//图片地址
String path = "C:\\Users\\QianSheng\\Desktop\\50.jpg";
File file = new File(path);
FileInputStream in = null;
Connection con = null;
PreparedStatement pre = null;
try {
//将file转为输入流
in = new FileInputStream(file);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
try {
con = DButil.getCon();
String sql = "insert into vegoods (id,vgname,details,price,vgimage,adminid)values(?,?,?,?,?,?)";
pre = con.prepareStatement(sql);
pre.setInt(1, 2);
pre.setString(2, "香蕉");
pre.setString(3, "香蕉大降价");
pre.setInt(4, 65);
pre.setBinaryStream(5, in, in.available());
pre.setInt(6, 1);
int i = pre.executeUpdate();
System.out.println(i);
} catch (SQLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
in.close();
DButil.dbClose(con, pre, null);
} catch (IOException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
结果: