JDBC存取二进制文件示例

时间:2021-09-22 22:49:21
PutFile.java
import java.io.File;
import java.io.FileInputStream;
import java.sql.*;


public class PutFile {


	public static void main(String args[]) {


		Connection conn = null;
		PreparedStatement psmd = null;
		String sql = null;


		try {
			conn = ConnUtil.getConn();
			File file = new File("F:\\1.jpg");// 要转换的文件 
			FileInputStream inputStream = new FileInputStream(file);// 将文件按二进制存储在一个字段内
			// CREATE TABLE images (imgname text, img bytea);
			sql = " insert into images values(?,?)";
			psmd = conn.prepareStatement(sql);
			psmd.setString(1, file.getName());
			psmd.setBinaryStream(2, inputStream, (int) file.length());			
			int rs = psmd.executeUpdate();


			if (rs < 0) {
				System.out.println("存入数据失败!!!");
			} else {
				System.out.println("存入数据成功!!!");
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		if (psmd != null) {
			try {
				psmd.close();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		if (conn != null) {
			try {
				conn.close();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}
}
GetFile.java
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.sql.*;

public class GetFile {

	public static void main(String args[]) {

		Connection conn = null;
		PreparedStatement psmd = null;
		String sql = null;
		OutputStream out = null;

		try {
			conn = ConnUtil.getConn();
			// CREATE TABLE images (imgname text, img bytea);
			sql = " SELECT img FROM images WHERE imgname = ?";
			psmd = conn.prepareStatement(sql);
			psmd.setString(1, "1.jpg");
			ResultSet rs = psmd.executeQuery();
			while(rs.next()) {
				byte[] imgBytes = rs.getBytes(1);
				// 实例化OutputStream对象,在f盘创建一个图片文件
				out = new FileOutputStream("f:\\2.jpg");
				// 将文件输出,内容则为byte数组里面的数据
				out.write(imgBytes);
				out.flush();
				System.out.println("获取数据成功!!!");		
			}
		} catch (Exception e) {
			e.printStackTrace();
		}

		if (psmd != null) {
			try {
				psmd.close();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		if (conn != null) {
			try {
				conn.close();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}

}
ConnUtil.java

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

public class ConnUtil {

	public static Connection getConn() {
		Connection conn = null;
		try {
			Class.forName("com.scistor.swift.jdbc.Driver"); // 驱动
			String url = "jdbc:swift://192.168.8.103:2345/swfit"; // 连接数据库的url
			try {
				conn = DriverManager.getConnection(url, "super", "111111"); // super 为数据库用户名,111111为密码
			} catch (SQLException e) {
				e.printStackTrace();
			}
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}

		return conn;
	}

}