图片等二进制数据在Mysql数据库的读写操作

如果要把图片等二进制数据存入数据库,要把数据库中的相应字段设为“blob”,Mysql数据库是这样,其他数据库可能有所不同。

测试代码:

 

/**
 * 图片等二进制数据的数据库插入、读取操作
 */
package test;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import mysql.base.JdbcUtils;

/**
 * 
 * 2009-9-25
 * 
 * 湖南大学 计算机与通信学院 计算机科学与技术专业
 * 
 * @author 陈春晓
 * 
 */
public class BlobTest {

	/**
	 * @param args
	 * @throws IOException
	 * @throws SQLException
	 */
	public static void main(String[] args) throws SQLException, IOException {
		// TODO Auto-generated method stub
		//create();
		read();
	}

	/**
	 * 插入数据
	 * 
	 * @throws SQLException
	 * @throws IOException
	 */
	public static void create() throws SQLException, IOException {
		String sqlStr = "insert into blob_test(big_bit) values(?)";
		Connection conn = null;
		PreparedStatement ps = null;
		try {
			// 注册驱动,只需要一次
			// Class.forName("com.mysql.jdbc.Driver");
			// 建立连接
			conn = JdbcUtils.getInstance().getConnection();
			// 创建语句
			ps = conn.prepareStatement(sqlStr);
			File file = new File("C:\\Documents and Settings\\Administrator\\桌面\\logo-yy.gif");
			InputStream in = new BufferedInputStream(new FileInputStream(file));
			ps.setBinaryStream(1, in, (int) file.length());
			// 执行语句
			ps.executeUpdate();
			// 关闭文件
			in.close();
		} finally {
			JdbcUtils.getInstance().free(null, ps, conn);
		}
	}

	/**
	 * 读取数据库
	 * 
	 * @throws SQLException
	 * @throws IOException
	 */
	public static void read() throws SQLException, IOException {
		String sqlStr = "select big_bit from blob_test";
		Connection conn = null;
		Statement st = null;
		ResultSet rs = null;
		try {
			// 建立连接
			conn = JdbcUtils.getInstance().getConnection();
			// 创建语句
			st = conn.createStatement();
			// 执行语句
			rs = st.executeQuery(sqlStr);
			// 处理结果
			while (rs.next()) {
				BufferedInputStream bis = new BufferedInputStream(rs.getBinaryStream("big_bit"));
				byte[] buf = new byte[1024];
				int len = 0;
				File file = new File("text.gif");
				BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(file));
				while ((len = bis.read(buf)) != -1) {
					bos.write(buf, 0, len);
				}
				bos.close();
			}
		} finally {
			JdbcUtils.getInstance().free(rs, st, conn);
		}
	}
}
 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值