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);
}
}
}