本文摘自PHP中文网,作者coldplay.xixi,侵删。
往mysql中添加图片的方法:首先创建一个方法使用FileInputStream读取图片;然后连接数据库并写入sql语句,用PreparedStatement执行sql语句。

本教程操作环境:windows7系统、mysql8.0.22版,该方法适用于所有品牌电脑。
相关免费学习推荐:mysql视频教程
往mysql中添加图片的方法:
1.效果

不是存了个字符串哈,可以看左边的数据类型。
2. 获取blob数据
我们创建一个方法使用FileInputStream
读取图片,还有ByteArrayOutputStream
将读取的数据写入byte[]数组,然后
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | 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);
}
byte[] array = out.toByteArray();
fis.close();
out.close();
return array ;
}
|
3.连接数据库并写入sql语句
使用Blob创建一个Blob,然后将我们获取的图片数据转换成blob类型,然后用PreparedStatement执行sql语句,因为它支持占位符并且有setBlob方法可以直接将我们的blob地址中的值写入数据库。然后就大功告成了。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 | 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中添加图片的详细内容,更多文章请关注木庄网络博客!
相关阅读 >>
开启mysql慢查询日志的方法
关于生产库中遇到mysql的子查询示例详解
教你如何查看mysql配置文件路径及相关配置
布尔教育燕十八mysql入门视频资料分享
mysql中b-tree引索和hash引索的区别?
mysql count distinct 统计结果去重
mysql怎么删除视图?
mysql中四种隔离级别的介绍
无法远程连接mysql怎么办
mysql数据库表格怎么建立
更多相关阅读请进入《mysql》频道 >>
机械工业出版社
本书主要讲述了数据模型、基于对象的数据库和XML、数据存储和查询、事务管理、体系结构等方面的内容。
转载请注明出处:木庄网络博客 » 如何往mysql中添加图片