package five.base;
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.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import five.utils.Utils;
//jdbc访问其他各种数据类型.参看数据库文档 例如23.3. MySQL Connector/J
// 图片 压缩包
public class ClobTest {
/**
* @param args
* @throws Exception
*/
public static void main(String[] args) throws Exception {
// create(3, "F:/下载/picture/X.bmp");
read(3);
}
public static void create(int id, String fileName) throws IOException {
Connection connection = null;
PreparedStatement ps = null;
ResultSet rs = null;
try {
connection = Utils.getConnection();
String sql = "insert into picture (id, picture) values (?,?)";
ps = connection.prepareStatement(sql);
File file = new File(fileName);
// 字节流
InputStream in = new BufferedInputStream(new FileInputStream(file));
ps.setInt(1, id);
// 前提 Ascii
// parameterIndex - the first parameter is 1, the second is 2, ...
// x - the Java input stream that contains the ASCII parameter value
// length - the number of bytes in the stream
// ps.setAsciiStream(2, x, length);
// 字节流
ps.setBinaryStream(2, in, (int) file.length());
int i = ps.executeUpdate();
in.close();
} catch (SQLException e) {
e.printStackTrace();
} finally {
Utils.free(connection, ps, rs);
}
}
static void read(int id) throws Exception {
// 避免依赖 应该使用接口(java.sql)的提供的类型
Connection connection = null;
PreparedStatement ps = null;
ResultSet rs = null;
try {
// 2 创建连接
connection = Utils.getConnection();
// 3 创建语句
String sql = "select picture from picture ";
ps = connection.prepareStatement(sql);
// 4 执行语句
rs = ps.executeQuery();
// 5 处理结果
while (rs.next()) {
// Blob blob = rs.getBlob(1);
// InputStream blobIn = blob.getBinaryStream();
// 等价于上面的语句
InputStream in = rs.getBinaryStream(1);
// rs.getCharacterStream(2);
File file = new File("D:/cgz/dayByDayJdbc/picture.bmp");
// 装饰模式
// Writer writer = new BufferedWriter(new FileWriter(file));
OutputStream out = new BufferedOutputStream(
new FileOutputStream(file));
// 字符流 new char[1024]
// 字节流 new byte[1024];
byte[] buff = new byte[1024];
for (int i = 0; (i = in.read(buff)) > 0;) {
out.write(buff, 0, i);
}
out.close();
in.close();
}
} finally {
Utils.free(connection, ps, rs);
}
}
}