记录一下
附件内容以文件流的形式保存到SQLServer中,现在将它提取出来并保存到本地
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.sql.*;
public class test {
public static void main(String[] args) throws SQLException {
String driverName = "com.microsoft.sqlserver.jdbc.SQLServerDriver";
String dbURL = "jdbc:sqlserver://192.168.1.1:1433;DatabaseName=master";
String userName = "test";
String userPwd = "123456";
Connection conn = null;
try {
Class.forName(driverName);
conn = DriverManager.getConnection(dbURL, userName, userPwd);
System.out.println("连接数据库成功");
} catch (Exception e) {
e.printStackTrace();
System.out.print("连接失败");
}
PreparedStatement prepare;
ResultSet result;
String sql = "SELECT FILE_NAME,EXT_NAME,FILE_CONTENT FROM SYS_ATTACH ";
prepare = conn.prepareStatement(sql);
result = prepare.executeQuery();
while (result.next()) {
String fileName = result.getString("FILE_NAME");
String extName = result.getString("EXT_NAME");
byte[] fileContent = result.getBytes("FILE_CONTENT");
String downloadName = fileName + "." + extName;
String filePath = "E:\\test\\";
getFile(fileContent, filePath, downloadName);
}
}
public static void getFile(byte[] bfile, String filePath, String fileName) {
BufferedOutputStream bos = null;
FileOutputStream fos = null;
File file = null;
try {
File dir = new File(filePath);
if (!dir.exists() && dir.isDirectory()) {
dir.mkdirs();
}
file = new File(filePath + "\\" + fileName);
fos = new FileOutputStream(file);
bos = new BufferedOutputStream(fos);
bos.write(bfile);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (bos != null) {
try {
bos.close();
} catch (IOException e1) {
e1.printStackTrace();
}
}
if (fos != null) {
try {
fos.close();
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
}
}