Blobタイプでデータベースに存在する画像をローカルに保存
3432 ワード
この文書では、blobタイプのSQLserverデータベースに存在するピクチャをJDBC形式でローカルにエクスポートします.
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(" ");
}
}