â æ们å¨æä½æ°æ®åå ¥blobæ°æ®çç±»å,常ç¨æ¥åå¨å¤´åå¾ççæµæ°æ®,blobç±»åå¦ææ³è¦åå¨æ¯è¾å¤§çæµæ件çæ°æ®,建议éç¨longBlobçæ°æ®ç±»å,Demoä¸çæ°æ®å°±ç®åç示èäºä¸ä¸,sqlæ件å¦ä¸:
DROP TABLE IF EXISTS `image_save`;
CREATE TABLE `image_save` (
`image_name` varchar(255) DEFAULT NULL,
`image_in` longblob
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
å¤å¶
â æå ¥å¾çå读åå¾çå°æ¬æºçæä½å¦ä¸:
public class BlobTest {
public static void main(String[] args) throws IOException, SQLException {
//æå¾çå为blobçæ ¼å¼å°æ°æ®åº
// storePicBlog();
//ä»æ°æ®åºè¯»åblobçæ ¼å¼çå¾çæ°æ®
getPicBlog();
}
public static void storePicBlog() throws FileNotFoundException, SQLException, IOException {
String m_dbDriver ="com.mysql.jdbc.Driver";
String m_dbUrl ="jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC";
Connection conn = DriverManager.getConnection(m_dbUrl, "root", "root");
File f = new File("C:\\Users\\admin\\Desktop\\timg.jpg");
FileInputStream fis = new FileInputStream(f);
String sql = "insert into image_save(image_name,image_in) values(?,?)";
PreparedStatement ps = conn.prepareStatement(sql);
ps.setString(1, "临æ¶å¾ç");
ps.setBinaryStream(2, fis, (int)f.length());
ps.executeUpdate();
conn.close();
ps.close();
}
public static void getPicBlog() throws FileNotFoundException, SQLException, IOException {
String m_dbDriver ="com.mysql.jdbc.Driver";
String m_dbUrl ="jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC";
Connection conn = DriverManager.getConnection(m_dbUrl, "root", "root");
File f = new File("C:\\Users\\admin\\Desktop\\timg.jpg");
FileInputStream fis = new FileInputStream(f);
String sql = "select image_in from image_save where image_name='临æ¶å¾ç'";
PreparedStatement ps = conn.prepareStatement(sql);
ResultSet rs = ps.executeQuery(sql);
Blob imageIn = null;
while (rs.next()){
imageIn = rs.getBlob("image_in");
}
InputStream in = imageIn.getBinaryStream();
OutputStream out = new FileOutputStream("C:\\Users\\admin\\Desktop\\cat.jpg");
byte[] buffer = new byte[1024];
int len = 0;
while((len = in.read(buffer)) != -1){
out.write(buffer, 0, len);
}
in.close();
out.close();
conn.close();
ps.close();
}
}
å¤å¶