2007/03/28

DataBase - 存取檔案至資料庫 (mssql2000)

環境:
DB : mssql 2000
Table schema :
id int,
fileContent image,
path varchar(255);

從檔案加入至資料庫

code:

try {
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
Connection con = DriverManager.getConnection("jdbc:sqlserver://127.0.0.1:1433", "cf-intermediate",
"cf-intermediate");

File file = new File("C:/MyEclipse5.1/workspace/myJava/abc.doc");
BufferedInputStream bufferedInputStream = new BufferedInputStream(new FileInputStream(file));

// 將檔案讀入位元陣列
ByteArrayOutputStream arrayOutputStream = new ByteArrayOutputStream();
byte[] bytes = new byte[1];

while (bufferedInputStream.read(bytes) != -1) {
arrayOutputStream.write(bytes);
}
arrayOutputStream.close();
bufferedInputStream.close();
bytes = arrayOutputStream.toByteArray();

System.out.println("bytes="+bytes.length);

PreparedStatement preState = con.prepareStatement("insert into erpglm_append values(?,?,?)");
preState.setBytes(1, bytes);
preState.setString(2, file.getPath());
preState.setString(3, "N");

preState.execute();
con.close();
} catch (Exception e) {
e.printStackTrace();
}


從資料庫取得資料並存成檔案:

try {
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
Connection con = DriverManager.getConnection("jdbc:sqlserver://127.0.0.1:1433", "cf-intermediate",
"cf-intermediate");

String sql = "select fileContent from erpglm_append where id=1";
Statement stat = con.createStatement();
ResultSet rs = stat.executeQuery(sql);
byte[] bytes = null;
while (rs.next()) {
bytes = (byte[]) rs.getObject("fileContent");
}
rs.close();
stat.close();
con.close();

System.out.println("bytes="+bytes.length);

BufferedInputStream bufferedInputStream = new BufferedInputStream(new ByteArrayInputStream(bytes));
File file = new File("C:/MyEclipse5.1/workspace/myJava/abc1.doc");
BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(new FileOutputStream(file));
byte[] data = new byte[1];
while (bufferedInputStream.read(data) != -1) {
bufferedOutputStream.write(data);
}
bufferedOutputStream.flush();
bufferedInputStream.close();
bufferedOutputStream.close();
} catch (Exception e) {
e.printStackTrace();
}

沒有留言:

NGINX SSL/設定檔案

#user nobody; worker_processes 1; #error_log logs/error.log; #error_log logs/error.log notice; #error_log logs/error.log info; #...