大对象存取
//BLOB和CLOB方法一样
package text;
import java.sql.Connection;
import java.sql.Statement;
import java.sql.SQLException;
import java.sql.PreparedStatement;
import java.io.File;
import java.io.FileInputStream;
import java.io.*;
import java.sql.ResultSet;
import oracle.sql.BLOB;
public class BLOBtest {
public static void createTab() { //建表
String sql = "create table myimg (id number,img blob)";
Connection con = DBConn.getConnection();
Statement stmt = null;
try {
stmt = con.createStatement();
stmt.execute(sql);
System.out.println("table created------");
}
catch (SQLException ex) {ex.printStackTrace();}
finally {
try {
stmt.close();
con.close();
}
catch (SQLException ex1) {
ex1.printStackTrace();
} } }
public static void insertData() { //插入大对象
Connection con =DBConn.getConnection();
PreparedStatement pstmt = null;
String sql = "insert into myimg values (?,?)";
try {
pstmt = con.prepareStatement(sql);
pstmt.setInt(1, 1000);
File file = new File("f:/jdbcdemo/2.jpg");
long len = file.length();
FileInputStream fis = new FileInputStream(file);
pstmt.setBinaryStream(2, fis, (int) len);
pstmt.execute();
System.out.println("insert pic success--------");
fis.close();
} catch (SQLException ex) {
ex.printStackTrace();
}catch (FileNotFoundException ex1) {
ex1.printStackTrace();
}catch (IOException ex2) {ex2.printStackTrace();}
finally {
try {
pstmt.close();
con.close();
}
catch (SQLException ex3) {
ex3.printStackTrace();
} } }
public static void getPic() { //下载大对象
Connection con = DBConn.getConnection();
Statement stmt = null;
ResultSet rst = null;
String sql = "select img from myimg where id = 1000";
try {
stmt = con.createStatement();
rst = stmt.executeQuery(sql);
while (rst.next()) {
File f = new File("f:/jdbcdemo/123.jpg");
FileOutputStream fos = new FileOutputStream(f);
BLOB blob = (BLOB) rst.getBlob(1);
InputStream is = blob.getBinaryStream();
DataInputStream dis = new DataInputStream(is);
int len;
len = dis.read();
while (len != -1) {
fos.write(len);
len = dis.read();
}
fos.close();
dis.close();
System.out.println("read finished-------------");
} }
catch (SQLException ex) { ex.printStackTrace();}
catch (FileNotFoundException ex1) {ex1.printStackTrace(); }
catch (IOException ex2) {ex2.printStackTrace();
}finally {
try {
stmt.close();
con.close();
}catch (SQLException ex3) {ex3.printStackTrace();}
} }
public static void main(String[] args) {
createTab();
insertData();
getPic();
}
}
Trackback: http://tb.blog.csdn.net/TrackBack.aspx?PostId=1205624