本实例演示图片的存储与读取:
/*
*@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);
}
}
}