import java.awt.image.BufferedImage;
import java.io.*;
import java.sql.*;
import javax.imageio.ImageIO;
import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGImageEncoder;
public class TestOracle {
String username, password;
Connection conn = null;
Statement stmt = null;
{
username = "potato";
password = "potato";
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
conn = DriverManager.getConnection(
"jdbc:oracle:thin:@192.168.0.146:1521:orcl", username,
password);
stmt = conn.createStatement();
} catch (Exception ex) {
System.out.println(ex);
}
}
public void blobInsert(String infile) throws Exception {
boolean defaultCommit = conn.getAutoCommit();
conn.setAutoCommit(false);
try {
System.out.println("try start");
stmt
.executeUpdate("INSERT INTO PICTURE (AID,PHOTO) VALUES('111',EMPTY_BLOB())");
System.out.println("stmt.executeUpdate");
// conn.commit();
ResultSet rs = stmt
.executeQuery("SELECT PHOTO FROM PICTURE WHERE AID='111' FOR UPDATE");
System.out.println("stmt.executeQuery");
while (rs.next()) {
oracle.sql.BLOB blob = (oracle.sql.BLOB) rs.getBlob("PHOTO");
System.out.println("rs.getBlob");
BufferedOutputStream out = new BufferedOutputStream(blob
.getBinaryOutputStream());
System.out.println("out stream create");
BufferedInputStream in = new BufferedInputStream(
new FileInputStream(new File(infile)));
System.out.println("Create new input file");
int c;
while ((c = in.read()) != -1) {
out.write(c);
}
in.close();
out.close();
}
conn.commit();
} catch (Exception ex) {
System.out.println("blobInsert's exception");
conn.rollback();
throw ex;
}
conn.setAutoCommit(defaultCommit);
}
public void blobGet() throws Exception {
// boolean defaultCommit = conn.getAutoCommit();
conn.setAutoCommit(false);
BufferedInputStream inputimage = null;
BufferedImage image =null;
FileOutputStream os=null;
try {
ResultSet rs = stmt
.executeQuery("SELECT PHOTO,ACODE FROM PICTURE WHERE ANAME='1'");
while (rs.next()) {
oracle.sql.BLOB blob = (oracle.sql.BLOB) rs.getBlob("PHOTO");
String acode=rs.getString("ACODE");
inputimage = new BufferedInputStream(blob.getBinaryStream());
image= ImageIO.read(inputimage);
System.out.println(acode);
os = new FileOutputStream("E:\\"+acode+"");
JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(os);
encoder.encode(image);
}
} catch (Exception ex) {
System.out.println("blobRead()'s exception" + ex);
conn.rollback();
throw ex;
}
conn.commit();
// conn.setAutoCommit(defaultCommit);
inputimage.close();
}
public static void main(String[] args) {
TestOracle test = new TestOracle();
try {
// test.blobInsert("D:\\ff.jpg");
test.blobGet();
} catch (Exception ex) {
System.out.println("main's test.blobInsert() Exception" + ex);
}
}
}
表结构
表名PHOTO
表字段AID varchar2(30);
PHOTO blob();