Java代码实现对sqlserver数据库表的image字段图片的读取,和输出存储到本地
由于表image字段图片存的内容是二进制值,如何输出保存到本地:
代码示例:(注:连接sqlserver数据库需配置其驱动文件)
public static void main(String[] args) {
try {
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
Connection con = DriverManager.getConnection("jdbc:sqlserver://192.168.xx.xx:1433;DatabaseName=xxxxxx", "username", "password");
Statement stmt = con.createStatement();
ResultSet rs;
String strSql = "SELECT ScanPage FROM table_name where field1 = 'xxxxxx'";
rs = stmt.executeQuery(strSql);
while (rs.next()) {
Blob blob = rs.getBlob("ScanPage");
InputStream in = blob.getBinaryStream();
DataOutputStream dos= new DataOutputStream(new BufferedOutputStream(new FileOutputStream( "D:/work/testdata/" + "xxxxxx_" + System.currentTimeMillis() + ".jpg")));
// 读出流
// in = rs.getBinaryStream("ScanPage");
int len = 0;
byte[] b = new byte[1024];
while ((len = in.read(b)) != -1) {
dos.write(b, 0, len);
}
dos.close();
in.close();
}
rs.close();
} catch (Exception e) {
e.printStackTrace();
}
}
运行: