如果要把图片等二进制数据存入数据库,要把数据库中的相应字段设为“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);
}
}
}