如何往mysql中添加图片
往mysql中添加图片的方法:首先创建一个方法使用FileInputStream读取图片;然后连接数据库并写入sql语句,用PreparedStatement执行sql语句。 本教程操作环境:windows7系统、mysql8.0.22版,该方法
往mysql中添加图片的方法:首先创建一个方法使用FileInputStream读取图片;然后连接数据库并写入sql语句,用PreparedStatement执行sql语句。
本教程操作环境:windows7系统、mysql8.0.22版,该方法适用于所有品牌电脑。
推荐:mysql视频教程
往mysql中添加图片的方法:
1.效果
不是存了个字符串哈,可以看左边的数据类型。
2. 获取blob数据
我们创建一个方法使用FileInputStream读取图片,还有ByteArrayOutputStream将读取的数据写入byte[]数组,然后
public static byte[] getImgStr(String path) throws IOException {
FileInputStream fis = new FileInputStream(path);
ByteArrayOutputStream out = new ByteArrayOutputStream();
int len = 0;
byte[] b = new byte[1024];
while ((len = fis.read(b))!= -1){
out.write(b,0,len);
}
//接收out
byte[] array = out.toByteArray();
fis.close();
out.close();
return array;
}
3.连接数据库并写入sql语句
使用Blob创建一个Blob,然后将我们获取的图片数据转换成blob类型,然后用PreparedStatement执行sql语句,因为它支持占位符并且有setBlob方法可以直接将我们的blob地址中的值写入数据库。然后就大功告成了。
public static void main(String[] args) {
/*
加载驱动
*/
try {
Class.forName("com.mysql.cj.jdbc.Driver");
//获取连接
String url = "jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC";
String user= "root";
String password ="123456";
try {
Connection connection = DriverManager.getConnection(url,user,password);
/*
插入图片
*/
byte[] arr = getImgStr("图片地址");
Blob blob = connection.createBlob();
blob.setBytes(1,arr);
String sql = "insert into pictures (name,pic,date) values('张三',?,'2015-01-01')";
PreparedStatement ps = connection.prepareStatement(sql);
ps.setBlob(1,blob);
ps.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
}
} catch (ClassNotFoundException | IOException e) {
e.printStackTrace();
}
}
推荐:php编程(视频)
以上就是如何往mysql中添加图片的详细内容,更多请关注每日运维其它相关文章!