插入
package com.study.jdbc;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
public class JDBC_blob_insert {
public static void main(String[] args) {
Connection conn = null;
PreparedStatement ps = null;
FileInputStream in = null;
try {
conn = DBUtil.getConnection();
String sql = "insert into t_img(name,img) values (?, ?)";
ps = conn.prepareStatement(sql);
ps.setString(1,"測試圖片");
in = new FileInputStream("F:\\Administrator\\Pictures\\1.jpg");
ps.setBlob(2, in);
int count = ps.executeUpdate();
System.out.println("插入" + count +"條數(shù)據(jù)");
} catch (SQLException | FileNotFoundException e) {
throw new RuntimeException(e);
} finally {
if(in != null){
try{
in.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
DBUtil.close(conn,ps,null);
}
}
}
查詢
package com.study.jdbc;
import java.io.*;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
public class JDBC_blob_query {
public static void main(String[] args) {
Connection conn = null;
PreparedStatement ps = null;
ResultSet rs = null;
try {
conn = DBUtil.getConnection();
String sql = "select img from t_img where name = ?";
ps = conn.prepareStatement(sql);
ps.setString(1,"測試圖片");
rs = ps.executeQuery();
while (rs.next()){
InputStream in = rs.getBinaryStream("img");// 通過結(jié)果集列名 獲取內(nèi)容 賦值給輸入流
OutputStream out = new FileOutputStream("E:/讀取文件.jpg"); // 定義一個輸出流將 內(nèi)容輸出到電腦指定位置
byte[] bytes = new byte[1024]; // 定義字節(jié)大小
int readCount = 0; // 讀取內(nèi)容初始值
while((readCount = in.read(bytes)) != -1){ // 當讀取的內(nèi)容 不為空時
out.write(bytes,0,readCount); // 將讀取的內(nèi)容寫入輸出流
}
out.flush(); // 刷新輸出流
in.close(); // 關(guān)閉輸入流
out.close(); // 關(guān)閉輸出流
}
} catch (SQLException e) {
throw new RuntimeException(e);
} catch (FileNotFoundException e) {
throw new RuntimeException(e);
} catch (IOException e) {
throw new RuntimeException(e);
} finally {
DBUtil.close(conn,ps,rs);
}
}
}
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。