binary data manipulation
package jdbc.test;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
public class BinaryManipulation {
public static int writeBinaryData() throws SQLException,
ClassNotFoundException, FileNotFoundException {
String sql = "insert into tabe_date_text_blob (image) values (?)";
PreparedStatement ps = JdbcMySqlUtil.getInstance().getPrepareStatement(
sql);
File file = new File("resource/Earth.bmp");
InputStream is = new BufferedInputStream(new FileInputStream(file));
ps.setBinaryStream(1, is, file.length());
int ret = ps.executeUpdate();
JdbcMySqlUtil.free(null, ps, ps.getConnection());
return ret ;
}
public static void readBinaryData() throws SQLException, ClassNotFoundException, IOException{
String sql = "select image from tabe_date_text_blob where id = 3";
PreparedStatement ps = JdbcMySqlUtil.getInstance().getPrepareStatement(
sql);
ResultSet rs = ps.executeQuery();
File file = new File("resource/Earth2.bmp");
InputStream is = null;
while (rs.next())
is = rs.getBinaryStream(1);
OutputStream os = new BufferedOutputStream(new FileOutputStream(file));
byte [] buf = new byte[1024];
int i = 0 ;
while ((i = is.read(buf)) > 0 )
os.write(buf, 0, i);
JdbcMySqlUtil.free(rs, ps, ps.getConnection());
}
public static void main(String[] args) throws ClassNotFoundException,
SQLException, IOException {
//print(writeBinaryData());
readBinaryData() ;
}
private static void print(Object obj) {
System.out.println(obj);
}
}
浙公网安备 33010602011771号