jdbc读取数据库图片文件

时间:2022-12-09 15:32:12
package 读取大文件.read;

import java.io.BufferedReader;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.sql.ResultSet;
import java.sql.Statement; import org.junit.Test; import 配置方式.dbUtils.Connection2;
/**
* 读取数据库中的问件
* @author lx
*
*/ public class ReadBlob {
@Test public void readBlob() throws Exception { // sql
String sql = "select * from stud where id=77";
// 读取不接受参数可以直接用statment Statement st = Connection2.GetCon().createStatement(); // 执行查询
ResultSet rs = st.executeQuery(sql);
// 确定只有一行
if (rs.next()) {
int id = rs.getInt("id");
// 获取图片
InputStream in = rs.getBinaryStream("img");// 数据库字段
// 声明out
OutputStream out = new FileOutputStream("q:/b.jpg"); byte[] b = new byte[1024];
int len = 0;
while ((len = in.read(b)) != -1) {
out.write(b, 0, len); }
out.close();
// --------------------------
// 显示文本
InputStream in2 = rs.getAsciiStream("id"); BufferedReader br = new BufferedReader(new InputStreamReader(in2)); String line = null;
while ((line = br.readLine()) != null) {
System.err.println(line); }
br.close();
in2.close(); } } }