主要的程序:
package greeds.jdbc.sample;
import greeds.jdbc.util.JDBCUtil;
import java.io.*;
import java.sql.*;
public class MySQLBlobSample {
public static void main(String[] args) throws Exception {
// 写入数据库
/*
*
* Connection conn = null; PreparedStatement pstm = null;
*
* try { String filepath = "D://strahovski-ep201-011.jpg"; File file =
* new File(filepath); FileInputStream fin = new FileInputStream(file);
* conn = JDBCUtil.getConnection();
*
* String sql = "insert into Dish(id,photo) values(?,?)"; pstm =
* conn.prepareStatement(sql); pstm.setInt(1, 3);
* pstm.setBinaryStream(2, fin,(int)file.length());
*
* int r = pstm.executeUpdate(); System.out.println("INSERT"+r+"ROW");
*
* fin.close();
*
*
* } catch (FileNotFoundException e) { e.printStackTrace(); } finally{
* //JDBCUtil.release(null, pstm, conn); }
*/
// 从数据库读取文件
Connection conn = null;
Statement stm = null;
ResultSet rs = null;
try {
conn = JDBCUtil.getConnection();
stm = conn.createStatement();
String sql = "select * from Dish where id=1";
rs = stm.executeQuery(sql);
rs.next();
Blob blob = rs.getBlob("photo");
FileOutputStream out = new FileOutputStream(new File("E:/my.jpg"));
InputStream in = blob.getBinaryStream();
int i;
while ((i = in.read()) != -1) {
out.write(i);
}
in.close();
out.close();
} catch (Exception e) {
e.printStackTrace();
} finally {
JDBCUtil.release(rs, stm, conn);
}
}
}
JDBCUtil.java程序
package greeds.jdbc.util;
import java.sql.*;
import java.io.InputStream;
import java.util.Properties;
public class JDBCUtil {
private static Properties env;
static {
try {
env = new Properties();
InputStream is = JDBCUtil.class
.getResourceAsStream("../config/conn.properties");
env.load(is);
is.close();
} catch (Exception e) {
e.printStackTrace();
throw new ExceptionInInitializerError(e);
}
}
public static final ThreadLocal<Connection>tl = new ThreadLocal<Connection>();
public static Connection getConnection() throws Exception {
Connection conn = tl.get();
if (conn == null) {
Class.forName(env.getProperty("driver"));
conn = DriverManager.getConnection(env.getProperty("url"), env
.getProperty("username"), env.getProperty("password"));
tl.set(conn);
}
return conn;
}
public static void release(ResultSet rs, Statement stm, Connection conn) {
if (rs != null)
try {
rs.close();
} catch (Exception e) {
}
if (stm != null)
try {
stm.close();
} catch (Exception e) {
}
if (conn != null)
try {
conn.close();
} catch (Exception e) {
}
}
}
配置文件 conn.properties
driver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/greedsdata?useUnicode=true&characterEncoding=utf-8
username=caps
password=caps
不能写入成功的主要原因是 红色字体处。