这篇文章给大家分享的是有关往mysql中添加图片的方法的内容。小编觉得挺实用的,因此分享给大家做个参考。一起跟随小编过来看看吧。

往mysql中添加图片的方法:首先创建一个方法使用FileInputStream读取图片;然后连接数据库并写入sql语句,用PreparedStatement执行sql语句。

相关免费学习推荐:mysql视频教程

往mysql中添加图片的方法:

1.效果

不是存了个字符串哈,可以看左边的数据类型。

2. 获取blob数据

我们创建一个方法使用FileInputStream读取图片,还有ByteArrayOutputStream将读取的数据写入byte[]数组,然后

publicstaticbyte[]getImgStr(Stringpath)throwsIOException{FileInputStreamfis=newFileInputStream(path);ByteArrayOutputStreamout=newByteArrayOutputStream();intlen=0;byte[]b=newbyte[1024];while((len=fis.read(b))!=-1){out.write(b,0,len);}//接收outbyte[]array=out.toByteArray();fis.close();out.close();returnarray;}

3.连接数据库并写入sql语句

使用Blob创建一个Blob,然后将我们获取的图片数据转换成blob类型,然后用PreparedStatement执行sql语句,因为它支持占位符并且有setBlob方法可以直接将我们的blob地址中的值写入数据库。然后就大功告成了。

publicstaticvoidmain(String[]args){/*加载驱动*/try{Class.forName("com.mysql.cj.jdbc.Driver");//获取连接Stringurl="jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC";Stringuser="root";Stringpassword="123456";try{Connectionconnection=DriverManager.getConnection(url,user,password);/*插入图片*/byte[]arr=getImgStr("图片地址");Blobblob=connection.createBlob();blob.setBytes(1,arr);Stringsql="insertintopictures(name,pic,date)values('张三',?,'2015-01-01')";PreparedStatementps=connection.prepareStatement(sql);ps.setBlob(1,blob);ps.executeUpdate();}catch(SQLExceptione){e.printStackTrace();}}catch(ClassNotFoundException|IOExceptione){e.printStackTrace();}}

感谢各位的阅读!关于往mysql中添加图片的方法就分享到这里了,希望以上内容可以对大家有一定的帮助,让大家可以学到更多知识。如果觉得文章不错,可以把它分享出去让更多的人看到吧!