介绍
这篇文章给大家分享的是有关往mysql中添加图片的方法的内容。小编觉得挺实用的,因此分享给大家做个参考。一起跟随小编过来看看吧。
往mysql中添加图片的方法:首先创建一个方法使用FileInputStream读取图片,然后连接数据库并写sql语入句,用PreparedStatement执行sql语句。
引用><强>相关免费学习推荐:强> <强> mysql视频教程强>
<强>往mysql中添加图片的方法:强>
<强> 1。效果强>
不是存了个字符串哈,可以看左边的数据类型。
<强> 2。获取blob数据强>
我们创建一个方法使用<代码> FileInputStream> 代码读取图片,还有<代码> ByteArrayOutputStream> 代码将读取的数据写入byte[]数组,然后
public static byte [], getImgStr (String 路径),throws IOException { ,,,,,,,FileInputStream fis =, new FileInputStream(路径); ,,,,,,,ByteArrayOutputStream out =, new ByteArrayOutputStream (); ,,,,,,,int len =, 0; ,,,,,,,byte [], b =, new 字节[1024]; ,,,,,,,while ((=len fis.read (b)) !=, 1) { ,,,,,,,,,,,out.write (b, 0, len); ,,,,,,,} ,,,,,,,//接收 ,,,,,,,byte [], array =, out.toByteArray (); ,,,,,,,fis.close (); ,,,,,,,out.close (); ,,,,,,,return 数组; ,,,}<强> 3。连接数据库并写入sql语句强>
使用Blob创建一个Blob,然后将我们获取的图片数据转换成Blob类型,然后用PreparedStatement执行sql语句,因为它支持占位符并且有setBlob方法可以直接将我们的团地址中的值写入数据库,然后就大功告成了。
,,,,public static void main (String [], args), { ,,,,,,/* ,,,,,,,加载驱动 ,,,,,,,*/,,,,,,,try { ,,,,,,,,,,,forname (“com.mysql.cj.jdbc.Driver"); ,,,,,,,,,,,//获取连接 ,,,,,,,,,,,String url =,“jdbc: mysql://localhost: 3306/测试? useUnicode=true& characterEncoding=UTF-8& serverTimezone=UTC"; ,,,,,,,,,,,String 用户=,“root"; ,,,,,,,,,,,String password =?23456”; ,,,,,,,,,,,try { ,,,,,,,,,,,,,,,Connection Connection =, DriverManager.getConnection (url、用户、密码); ,,,,,,,,,,,,,,/* ,,,,,,,,,,,,,,,插入图片 ,,,,,,,,,,,,,,,*/,,,,,,,,,,,,,,,byte [], arr =, getImgStr(“图片地址“); ,,,,,,,,,,,,,,,Blob Blob =, connection.createBlob (); ,,,,,,,,,,,,,,,blob.setBytes (arr); ,,,,,,,,,,,,,,,String sql =,“insert into pictures (名称、图片、日期),值(& # 39;张三& # 39;,?,& # 39;2015 - 01 - 01 & # 39;)“; ,,,,,,,,,,,,,,,PreparedStatement ps =, connection.prepareStatement (sql); ,,,,,,,,,,,,,,,ps.setBlob (blob); ,,,,,,,,,,,,,,,ps.executeUpdate (); ,,,,,,,,,,,},catch (SQLException e), { ,,,,,,,,,,,,,,,e.printStackTrace (); ,,,,,,,,,,,} ,,,,,,,},catch (ClassNotFoundException |, IOException e), { null null null往mysql中添加图片的方法