共計 1629 個字符,預計需要花費 5 分鐘才能閱讀完成。
自動寫代碼機器人,免費開通
這篇文章給大家分享的是有關(guān)往 mysql 中添加圖片的方法的內(nèi)容。丸趣 TV 小編覺得挺實用的,因此分享給大家做個參考。一起跟隨丸趣 TV 小編過來看看吧。
往 mysql 中添加圖片的方法:首先創(chuàng)建一個方法使用 FileInputStream 讀取圖片;然后連接數(shù)據(jù)庫并寫入 sql 語句,用 PreparedStatement 執(zhí)行 sql 語句。
相關(guān)免費學習推薦:mysql 視頻教程
往 mysql 中添加圖片的方法:
1. 效果
不是存了個字符串哈,可以看左邊的數(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)于往 mysql 中添加圖片的方法就分享到這里了,希望以上內(nèi)容可以對大家有一定的幫助,讓大家可以學到更多知識。如果覺得文章不錯,可以把它分享出去讓更多的人看到吧!
向 AI 問一下細節(jié)
丸趣 TV 網(wǎng) – 提供最優(yōu)質(zhì)的資源集合!