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 {
// 定义 JDBC 驱动串
String jdbcString = "com.mysql.jdbc.Driver";
// 定义 URL 连接串
String urlString = "jdbc:mysql://127.0.0.1:3306/test?useUnicode=true&characterEncoding=utf-8&allowMultiQueries=true";
// 定义连接用户名
String userName = "cccc";
// 定义连接用户口令
String password = "cccc";
// 定义连接对象
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...");
// 连接 数据库
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 thumb";
ps = conn.prepareStatement(sql);
rs = ps.executeQuery();
String s1 = "";
//将图片存放到本地的路径
String s = "E:\\image\\";
while (rs.next()) {
System.out.println("thumb_" + rs.getInt("id")+".jpg");
Blob blob = rs.getBlob("thumb");
if(blob == null){
continue;
}
//验证图片路径是否存在,不存在就创建
File f = new File(s);
if(!f.exists()){
f.mkdirs();
}
s1 = s + "thumb_" + rs.getInt("id")+".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("数据库连接关闭");
}
}