存取数据库图片

来源:互联网 发布:大数据分析师工资 编辑:程序博客网 时间:2024/06/05 21:12
数据库存储图片的字段类型   bolb  数据大的图片为Longbolb




  存:
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static void main(String[] args) {

try(Connection connection=DriverManager.getConnection("jdbc:mysql://localhost:3306/mybatis?userUnicode=true&charsetEncoding=utf8", "root", "root")){
String sql="insert into tb_text(id,img,name) values(default,?,?)";
PreparedStatement ps = (PreparedStatement) connection.prepareStatement(sql);
InputStream inputStream = Test4.class.getResourceAsStream("123.jpg");
ps.setBinaryStream(1,inputStream);
ps.setString(2, "123.jpg");
if(ps.executeUpdate()==1){
System.out.println("存储成功");
}
}catch(Exception e){
e.printStackTrace();
}





  取:
try(Connection connection=DriverManager.getConnection("jdbc:mysql://localhost:3306/mybatis?userUnicode=true&charsetEncoding=utf-8", "root", "root")){
String sql="select * from tb_text where id=?";
PreparedStatement ps = connection.prepareStatement(sql);
ps.setInt(1, 1);
ResultSet rs = ps.executeQuery();
if(rs.next()){
try(InputStream input = rs.getBinaryStream("img")){
Path path = Paths.get("com.dp.a.jpg");
Files.copy(input, path);
}

}
}catch(Exception e){
e.printStackTrace();
}
原创粉丝点击