本文以JDBC格式将blob类型存在SQLserver数据库的图片导出到本地
package com.wenhua.dl_guihua.action;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.sql.Blob;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class TestPic {
// 定义 DM JDBC 驱动串
String jdbcString = "com.microsoft.sqlserver.jdbc.SQLServerDriver";
// 定义 DM URL 连接串
String urlString = "jdbc:sqlserver://192.168.1.203:1433; DatabaseName=DL";
// 定义连接用户名
String userName = "sa";
// 定义连接用户口令
String password = "root";
// 定义连接对象
static Connection conn = null;
static Statement stmt = null;
static PreparedStatement ps = null;
static ResultSet rs = null;
/*
* 加载 JDBC 驱动程序
*
* @throws SQLException 异常
*/
public void loadJdbcDriver() throws SQLException {
try {
System.out.println("Loading JDBC Driver...");
// 加载 JDBC 驱动程序
Class.forName(jdbcString);
} catch (ClassNotFoundException e) {
throw new SQLException("Load JDBC Driver Error1: " + e.getMessage());
} catch (Exception ex) {
throw new SQLException("Load JDBC Driver Error : " + ex.getMessage());
}
}
public void connect() throws SQLException {
try {
System.out.println("Connecting to DM Server...");
// 连接 DM 数据库
conn = DriverManager.getConnection(urlString, userName, password);
System.out.println("数据库连接成功!");
} catch (SQLException e) {
throw new SQLException("Connect to DM Server Error : " + e.getMessage());
}
}
/*
* 关闭连接
*
* @throws SQLException 异常
*/
public void disConnect() throws SQLException {
try {
// 关闭连接
conn.close();
System.out.println("close");
} catch (SQLException e) {
throw new SQLException("close connection error : " + e.getMessage());
}
}
public static void main(String args[]) throws IOException, SQLException {
TestPic basicApp = new TestPic();
// 加载驱动程序
basicApp.loadJdbcDriver();
basicApp.connect();
// 读取图片出来,保存到本地的磁盘上面
// String sql = "SELECT * FROM ManagementWeb_Information_pic";
String sql = "SELECT * FROM test";
ps = conn.prepareStatement(sql);
rs = ps.executeQuery();
String s1 = "";
//将图片存放到本地的路径
String s = "E:\\工作专用\\大连规划\\图片分类\\信息动态\\综合信息\\";
while (rs.next()) {
System.out.println("图片名: " + rs.getInt("id")+ "_" + rs.getInt("info_id")+"_"+ rs.getString("title")+".jpg");
Blob blob = rs.getBlob("pic");
if(blob == null){
continue;
}
//验证图片路径是否存在,不存在就创建
File f = new File(s);
if(!f.exists()){
f.mkdirs();
}
s1 = s + rs.getInt("id")+ "_" + rs.getInt("info_id")+"_"+ rs.getString("title").replace("\"", "")+".jpg";
File file2 = new File(s1);
OutputStream outputStream = new FileOutputStream(file2);
try {
//blob.getBytes的第一个参数是从第几个字节开始提取数据,第二个是提取字节的长度
outputStream.write(blob.getBytes(1, (int) blob.length()));
} catch (IOException e) {
e.printStackTrace();
}
}
basicApp.disConnect();
System.out.println("数据库连接关闭");
}
}