Class.forName("com.mysql.jdbc.Driver");
//System.out.print("加載驅動完畢");
String url="jdbc:mysql://localhost:3306/studentmanager";
String username="root";
String password="root";
String sql1="select * from images";
Connection conn=DriverManager.getConnection(url,username,password);
//創建一個 Statement 對象來將 SQL 語句發送到數據庫。
PreparedStatement pst=conn.prepareStatement(sql1);
ResultSet rs=pst.executeQuery();
rs.next();
//從ResultSet中得到Blob的對象
Blob b=rs.getBlob("img");
//通過Blob對象的getBinaryStream得到字節流
InputStream fis= b.getBinaryStream();
//構建字節流的緩存BufferedInputStream的對象
BufferedInputStream bis=new BufferedInputStream(fis);
//準備一個FileOutputStream輸出流對象
FileOutputStream fos =new FileOutputStream("d://2.jpg");
//準備一個字節數組,以備緩存讀對象BufferedInputStream,每次讀這些字節長度
byte[] be=new byte[1024];
//每讀1024個字節就向FileOutputStream寫1024個字節,直到寫完。
while((bis.read(be))!=-1){
fos.write(be);
}
fos.flush();
fos.close();
fis.close();
bis.close();
} catch (Exception ex) {
ex.printStackTrace();
}
}
public void write(){
try {
Class.forName("com.mysql.jdbc.Driver");
//System.out.print("加載驅動完畢");
String url="jdbc:mysql://localhost:3306/studentmanager";
String username="root";
String password="root";
String sql1="insert into images values (?)";
Connection conn=DriverManager.getConnection(url,username,password);
//創建一個 Statement 對象來將 SQL 語句發送到數據庫。
PreparedStatement pst=conn.prepareStatement(sql1);
File file=new File("e://1.jpg");
int len=(int)file.length();
FileInputStream fis=new FileInputStream(file);
pst.setBinaryStream(1,fis,len);
int count=pst.executeUpdate();
if(count>0){
System.out.println("執行成功");
}else{
System.out.println("執行未返回任何影響行數");
}
} catch (Exception ex) {
ex.printStackTrace();
}