JDBC-二进制文件的存储与读取

本实例演示图片的存储与读取:

/*
 *@Author swxctx
 *@time 2016年7月22日
 */
/*访问二进制数据*/
package base.jdbc;

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.io.OutputStream;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import com.mysql.jdbc.Connection;
import com.mysql.jdbc.PreparedStatement;

public class jbit_img {

	public static void main(String[] args) throws ClassNotFoundException, SQLException, IOException {
		// TODO Auto-generated method stub

		//create();
		read();
	}

	//添加数据
	static void create() throws ClassNotFoundException, SQLException, IOException{
		Connection conn=null;//建立连接
		PreparedStatement ps=null;//创建语句
		ResultSet rs=null;//执行语句
		try {
			Class.forName("com.mysql.jdbc.Driver");//注册驱动
			conn=tools.getConnection();//建立连接
			
			String creat="insert into bit_img(big_bit) values(?)";
			ps=(PreparedStatement) conn.prepareStatement(creat);//建立语句
			
			File file=new File("src/zhu.jpg");//读取文件
			InputStream in=new BufferedInputStream(new FileInputStream(file));//字节流
			ps.setBinaryStream(1, in, (int)file.length());
			
			//新增记录(执行语句)
			int i=ps.executeUpdate();
			in.close();//关闭文件
			
			if(i==1){
				System.out.println("Success...");
			}
			else{
				try {
					System.out.println("Failed...");
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}finally{//释放资源
				tools.free(rs, ps, conn);
		}
	}
	
	//读取数据		
	static void read() throws SQLException,IOException{
		Connection conn=null;//建立连接
		Statement st=null;//创建语句
		ResultSet rs=null;//执行语句
		try {
//			Class.forName("com.mysql.jdbc.Driver");//注册驱动
			conn=tools.getConnection();//建立连接
			st=conn.createStatement();//建立语句
			
			rs=st.executeQuery("select big_bit from bit_img");//执行语句
			
			//处理结果
			while(rs.next()){
//				Blob blo=rs.getBlob(1);//读取出
//				InputStream in=blo.getBinaryStream();//读取字节流
				
				InputStream in=rs.getBinaryStream(1);//直接读取
				File file=new File("jbit_img.jpg");
				OutputStream out=new BufferedOutputStream(new  FileOutputStream(file));//另存到文件
				byte[] buffer=new byte[1024];//定义缓冲区
				for(int i=0;(i=in.read(buffer))>0;){
					out.write(buffer, 0, i);//写入
				}
				out.close();//关闭
				in.close();
			}
		}finally{//释放资源
				tools.free(rs, st, conn);
			}
	}
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Swxctx

您的鼓励将是我创作的最大动力!

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值