key words : blob , oracle ,插入图片
come from here
显示blob
try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver").newInstance();
Connection con=DriverManager.getConnection("jdbc:odbc:Multimedia","samp","samp");
Statement stmt=con.createStatement();
ResultSet rs=stmt.executeQuery("select frame from MULTIMEDIA_TAB where clip_id=1");
if(rs.next()){
try {
InputStream dis=rs.getBinaryStream(1);
byte[] x = new byte [10*1024]; //creare byte array to hold the blob data
int lengthRead = 0; // Number of bytes read
String fileToWriteBlob = "./default-app/MyProgs/ImageRetrieval/ganpati.jpg";
FileOutputStream outputStream = new FileOutputStream(fileToWriteBlob);
while( (lengthRead =dis.read(x)) != -1){
outputStream.write(x);
}
dis.close();
outputStream.close();
}
catch(Exception e) {
System.out.println ("Error is : " + e);
}
}
}
catch
(Exception ex)
{
System.out.println("Error " + ex);
}
If you are inserting a row:
1.Insert the row with all values, but insert an empty blob into the blob column:
"INSERT INTO yourtable (id,blob_value) VALUES (?,empty_blob())"
2. Select the empty blob you created:
"SELECT blob_value FROM yourtable WHERE id=?"
oracle.sql.BLOB blob = rs.getBLOB("blob_value");
(some code is of course missing, but this should give you the idea)
3. Write the bytes into the blob:
try {
OutputStream outstream = blob.getBinaryOutputStream();
outstream.write(blobValue);
outstream.flush();
outstream.close();
} catch (IOException e) {
// handle exception
}
Where blobValue is the byte array containing the image data.
4. Update the row:
"UPDATE yourtable SET blob_value=? WHERE id=?"
pstmt.setBLOB(1, blob);
pstmt.setInt(2, id);
(NOTE: the setBLOB is an Oracle specific method, you can probably also use the setBlob method).
Again, some essential code concerning the prepared statements is missing, but this should give you an idea...
That's that. If you just need to update the row, you just go through steps 2-4 above.
Here is an example:
import
java.sql.
*
;
import
java.io.
*
;
public
class
imgtest
{
private PreparedStatement ps = null;
private Connection conn = null;
public void initialise() {
String URL = "jdbc:oracle:thin:@localhost:1521:SID";
String userid = "user";
String passwd = "pass";
// register the JDBC driver
try {
DriverManager.registerDriver(new
oracle.jdbc.driver.OracleDriver());
// get a connection
Connection conn = DriverManager.getConnection(URL, userid, passwd);
this.conn = conn;
// create a prepared statement
ps = conn.prepareStatement("INSERT INTO images (NAME,IMAGE) VALUES (?,?)");
}
catch (Exception e) {
System.out.println("Error: " + e);
System.exit(1);
}
}
public imgtest() {
initialise();
File fImage = null;
FileInputStream isImage = null;
try {
fImage = new File( "fileo.gif" );
isImage = new FileInputStream( fImage );
}
catch (FileNotFoundException fnf) {
System.out.println("File not found: " + fnf);
System.exit(1);
}
try {
ps.setString(1,"Open File");
ps.setBinaryStream(2,isImage,(int)(fImage.length()));
ps.executeUpdate();
ps.close();
conn.close();
}
catch (Exception e) {
System.out.println("Error: " + e);
System.exit(1);
}
}
public static void main(String[] args) {
new imgtest();
}
}
My table looks like this:
// ---->%----
CREATE TABLE images
(NAME VARCHAR2(16) primary key not null,
IMAGE BLOB(64k));
commit;
quit;
// ---->%----
update(2007-5-13)
/** */
/**
* Oracle中的Blob类型字段操作
* User: Alex
* Date: 2007-5-9
* Time: 16:42:43
*/
public
class
BlobUtil
{
/** *//**
* 获得blob内容
*
* @param documentId : 文档编号
* @param response : HttpServletResponse
*/
public static void downloadDocument(String documentId, HttpServletResponse response) {
if (null == documentId) throw new JyhdException("文档编号为空,请检查");
DbDao db = null;
ResultSet rs = null;
BLOB blob = null;
OutputStream out = null;
try {
String sql = "select id,file_blob from tbl_blob_document where id = " + documentId;
db = new DbDaoImpl();
rs = db.query(sql);
if (rs.next()) {
blob = (BLOB) rs.getBlob("file_blob");
InputStream in = blob.getBinaryStream();
out = response.getOutputStream();
int size = blob.getBufferSize();
byte[] buffer = new byte[size]; // 建立缓冲区
int len;
while ((len = in.read(buffer)) != -1)
out.write(buffer, 0, len);
}
}
catch (Exception e) {
e.printStackTrace();
throw new JyhdException("===>>>table非法");
}
finally {
try {
if (null != out) {
out.close();
}
if (null != db) {
db.close();
}
} catch (Exception ee) {
ee.printStackTrace();
}
}
}
/** *//**
* 插入blob内容
* updated: 支持update,动态判断documentId是否已经存在,若已经存在则修改
*
* @param inputStream : 读取输入流
* @param documentId : 请从WellsoonUtil.getSequence("TBL_BLOB_DOCUMENT_SEQ") 获取
*/
public static void uploadDocument(InputStream inputStream, String documentId) {
DbDao db = null;
ResultSet rs = null;
Connection conn = null;
String sql = null;
try {
db = new DbDaoImpl();
conn = db.getConnection();
conn.setAutoCommit(false);
Statement stmt = conn.createStatement();
//如果已经存在则更新
String hasOldRecord = "select id from tbl_blob_document where id =" + documentId;
if (!DbUtil.hasRecord(hasOldRecord)) {
sql = "insert into tbl_blob_document( id,file_blob) values(" + documentId + ",EMPTY_BLOB())";
int count = stmt.executeUpdate(sql);
}
//select for update
sql = "select id,file_blob from tbl_blob_document where id = " + documentId + " for update";
rs = stmt.executeQuery(sql);
if (rs.next()) {
BLOB blob = ((OracleResultSet) rs).getBLOB("file_blob"); // 得到BLOB对象
OutputStream out = blob.getBinaryOutputStream(); // 建立输出流
int size = blob.getBufferSize();
byte[] buffer = new byte[size]; // 建立缓冲区
int len;
while ((len = inputStream.read(buffer)) != -1)
out.write(buffer, 0, len);
inputStream.close();
out.close();
}
conn.commit();
}
catch (Exception e) {
e.printStackTrace();
throw new JyhdException("===>>>table非法");
}
finally {
try {
db.close();
} catch (Exception ee) {
ee.printStackTrace();
}
}
}
/** *//**
* 填充Blob
*/
private static void fillBlob(oracle.sql.BLOB blob, byte[] btaData) throws Exception {
int len = btaData.length;
long num = 0;
byte[] btBlockData;
for (int i = 0; i < len; i += num) {
if (i == 0)
btBlockData = btaData;
else {
btBlockData = new byte[len - i];
System.arraycopy(btaData, i, btBlockData, 0, len - i);
}
num = blob.putBytes(i + 1, btBlockData);
}
}
/** *//**
* dump Blob
*
* @param blob
* @return
* @throws Exception
*/
private static byte[] dumpBlob(oracle.sql.BLOB blob) throws Exception {
long len = blob.length();
byte[] byte0 = new byte[(int) len];
byte[] byte1 = new byte[32512];
int num = 0;
for (int i = 0; i < len; i += num) {
num = blob.getBytes(i + 1, (int) len - i, byte1);
System.arraycopy(byte1, 0, byte0, i, num);
}
byte1 = null;
return byte0;
}
public static void main(String[] args) throws Exception {
//文件上传
File file = new File("Y:\\我的照片\\Palm\\Photo_121306_013.jpg");
InputStream in = new FileInputStream(file);
String sequence = SequenceUtil.getSequence("TBL_BLOB_DOCUMENT_SEQ");
uploadDocument(in, sequence);
}
}
http://www.blogjava.net/alex/archive/2007/03/28/107018.aspx