如何往mysql中添加圖片

mysql中添加圖片的方法:首先創(chuàng)建一個方法使用FileInputStream讀取圖片;然后連接數(shù)據(jù)庫并寫入sql語句,用PreparedStatement執(zhí)行sql語句。

如何往mysql中添加圖片

本教程操作環(huán)境:windows7系統(tǒng)、mysql8.0.22版,該方法適用于所有品牌電腦。

相關(guān)免費學(xué)習(xí)推薦:mysql視頻教程

往mysql中添加圖片的方法:

1.效果

如何往mysql中添加圖片

不是存了個字符串哈,可以看左邊的數(shù)據(jù)類型

2. 獲取blob數(shù)據(jù)

我們創(chuàng)建一個方法使用FileInputStream讀取圖片,還有ByteArrayOutputStream將讀取的數(shù)據(jù)寫入byte[]數(shù)組,然后

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.連接數(shù)據(jù)庫并寫入sql語句

使用Blob創(chuàng)建一個Blob,然后將我們獲取的圖片數(shù)據(jù)轉(zhuǎn)換成blob類型,然后用PreparedStatement執(zhí)行sql語句,因為它支持占位符并且有setBlob方法可以直接將我們的blob地址中的值寫入數(shù)據(jù)庫。然后就大功告成了。

????public?static?void?main(String[]?args)?{ ????????/* ????????加載驅(qū)動 ?????????*/ ????????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(); ????????} ????}

相關(guān)免費學(xué)習(xí)推薦:mysql視頻教程(視頻)

以上就是如何往

? 版權(quán)聲明
THE END
喜歡就支持一下吧
點贊6 分享