import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
/*
* 使用jdbc資料庫的employee表格新增名為photo之欄位(欄位型態使用varbinary(MAX))儲存圖檔
* 準備5張圖片,副檔名需一致,且檔名與員工編號相同,並儲在res資料夾中,此程式使用:1001.jpg、1002.jpg....1005.jpg
* 以批次方式(addBatch()、executeBatch())寫入資料庫
*/
public class PictureInputHomeWork3 {
public static void main(String[] args) throws IOException {
Connection conn = null;
PreparedStatement stmt=null;
File f =null;
FileInputStream fis=null;
try {
String connUrl = "jdbc:sqlserver://localhost:1433;databaseName=jdbc";
conn = DriverManager.getConnection(connUrl, "sa", "passw0rd");
//使用UPDATE指令新增相片
String qryStmt = "UPDATE employee SET photo=? WHERE empno=?"; 
stmt = conn.prepareStatement(qryStmt);


for(int i=1001 ;i<=1005;i++){ //依員工編號塞入對應之圖檔
//圖片的存放位置,將圖片依員工編號取名,是為了方便使用for迴圈寫入資料庫
f = new File("D:/JDBC/workspace/JDBCHomeWork/res/"+i+".jpg");
//為了配合setBinaryStream,因此使用InputStream將File轉成byte型態
fis = new FileInputStream(f);

//圖片是二進位檔(byte方式儲存),因此要使用setBinaryStream();f.length()代表圖檔容量
stmt.setBinaryStream(1, fis, f.length());//第一個?儲存圖片
stmt.setInt(2,i);//第二個?為員工編號
stmt.addBatch(); 
}
stmt.executeBatch(); //批次寫入資料庫

} catch (SQLException e) {
e.printStackTrace();
}finally{
fis.close(); //關閉檔案
if(stmt!=null)
try {
stmt.close();
} catch (SQLException e) {

e.printStackTrace();
}
if(conn!=null)
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}

 

arrow
arrow
    文章標籤
    jdbc
    全站熱搜

    goodice0728 發表在 痞客邦 留言(0) 人氣()