本文目錄一覽:
- 1、blob欄位java如何處理
- 2、使用java語言操作,如何來實現MySQL中Blob欄位的存取
- 3、java怎樣創建一個blob對象
- 4、java中blob類型是什麼類型
- 5、java 關於blob類型問題
- 6、如何在java中讀取oracle blob
blob欄位java如何處理
1.使用jdk中的方法進行傳輸。在ResultSet 中有getBlob()方法,在PreparedStatement中有setBlob()方法,所以大多數人都會嘗試setBlob
(),getBlob() 進行讀寫,或者兩個資料庫之間BLOB的傳輸。這種方法實際上是行不通的,據網上的一些資料介紹,說sun官方的文檔有些方法
都是錯誤的。
2.使用ResultSet.getBinaryStream 和PreparedStatement.setBinaryStream對BLOB進行讀寫或兩個資料庫間的傳輸。這種方法我自己嘗試過,
發現,如果BLOB中存儲的是文本文件的話,就沒問題,如果是二進位文件,傳輸就會有問題。
根據自己的經驗,以及查閱了Oracle的官方文檔,都是使用如下處理方法:
1.新建記錄,插入BLOB數據
1.1首先新建記錄的時候,使用oracle的函數插入一個空的BLOB,假設欄位A是BLOB類型的:
insert xxxtable(A,B,C) values(empty_blob(),’xxx’,’yyyy’)
1.2後面再查詢剛才插入的記錄,然後更新BLOB,在查詢前,注意設置Connection的一個屬性:
conn.setAutoCommit(false);如果缺少這一步,可能導致fetch out of sequence等異常.
1.3 查詢剛才插入的記錄,後面要加「 for update 」,如下:
select A from xxxtable where xxx=999 for update ,如果缺少for update,可能出現row containing the LOB value is not locked
的異常
1.4 從查詢到的 BLOB欄位中,獲取blob並進行更新,代碼如下:
BLOB blob = (BLOB) rs.getBlob(“A”);
OutputStream os = blob.getBinaryOutputStream();
BufferedOutputStream output = new BufferedOutputStream(os);
後面再使用output.write方法將需要寫入的內容寫到output中就可以了。例如我們將一個文件寫入這個欄位中:
BufferedInputStream input = new BufferedInputStream(new File(“c://hpWave.log”).toURL().openStream());
byte[] buff = new byte[2048]; //用做文件寫入的緩衝
int bytesRead;
while(-1 != (bytesRead = input.read(buff, 0, buff.length))) {
output.write(buff, 0, bytesRead);
System.out.println(bytesRead);
}
上面的代碼就是從input里2k地讀取,然後寫入到output中。
1.5上面執行完畢後,記得關閉output,input,以及關閉查詢到的ResultSet
1.6最後執行conn.commit();將更新的內容提交,以及執行conn.setAutoCommit(true); 改回Connction的屬性
2.修改記錄,方法與上面的方法類似,
2.1首先更新BLOB以外的其他欄位
2.2 使用1.3中類似的方法獲取記錄
2.3 修改的過程中,注意以下:a 需要更新的記錄中,BLOB有可能為NULL,這樣在執行blob.getBinaryOutputStream()獲取的值可能為
null,那麼就關閉剛才select的記錄,再執行一次update xxxtable set A = empty_blob() where xxx, 這樣就先寫入了一個空的BLOB(不是null),然後再
使用1.3,1.4中的方法執行更新記錄.b 注意別忘了先執行setAutoCommit(false),以及”for update”,以及後面的conn.commit();等。
3.讀取BLOB欄位中的數據.
3.1 讀取記錄不需要setAutoCommit(),以及 select ….for update.
3.2 使用普通的select 方法查詢出記錄
3.3 從ResultSet中獲取BLOB並讀取,如下:
BLOB b_to = (BLOB) rs.getBlob(“A”);
InputStream is = b_from.getBinaryStream();
BufferedInputStream input = new BufferedInputStream(is);
byte[] buff = new byte[2048];
while(-1 != (bytesRead = input.read(buff, 0, buff.length))) {
//在這裡執行寫入,如寫入到文件的BufferedOutputStream里
System.out.println(bytesRead);
}
通過循環取出blob中的數據,寫到buff里,再將buff的內容寫入到需要的地方
4.兩個資料庫間blob欄位的傳輸
類似上面1和3的方法,一邊獲取BufferedOutputStream,另外一邊獲取BufferedInputStream,然後讀出寫入,需要注意的是寫入所用的
Connection要執行conn.setAutoCommit(false);以及獲取記錄時添加「 for update 」以及最後的commit();
總結以上方法,其根本就是先創建空的BLOB,再獲取其BufferedOutputStream進行寫入,或獲取BufferedInputStream進行讀取
(1)對資料庫clob型執行插入操作
*************************************************
java.sql.PreparedStatement pstmt = null;
ResultSet rs = null;
String query = “”;
conn.setAutoCommit(false);
query = “insert into clobtest_table(id,picstr) values(?,empty_clob())”;
java.sql.PreparedStatement pstmt = conn.prepareStatement(query);
pstmt.setString(1,”001″);
pstmt.executeUpdate();
pstmt = null
query = “select picstr from clobtest_table where id = ‘001’ for update”;
pstmt = con.prepareStatement(query)
rs= pstmt.executeQuery();
oracle.sql.CLOB clobtt = null;
if(rs.next()){
clobtt = (oracle.sql.CLOB)rs.getClob(1);
}
Writer wr = clobtt.getCharacterOutputStream();
wr.write(strtmp);
wr.flush();
wr.close();
rs.close();
con.commit();
(2)通過sql/plus查詢是否已經成功插入資料庫
*************************************************
PL/SQL的包DBMS_LOB來處理LOB數據。察看剛才的插入是否成功。使用DBMS_LOB包的getlength這個procedure來檢測是否已經將str存入到picstr欄位中了。如:
SQL select dbms_lob.getlength(picstr) from clobtest_table;
(3)對資料庫clob型執行讀取操作
*************************************************
讀取相對插入就很簡單了。基本步驟和一半的取資料庫數據沒有太大的差別。
String description = “”
query = “select picstr from clobtest_table where id = ‘001’”;
pstmt = con.prepareStatement(query);
ResultSet result = pstmt.executeQuery();
if(result.next()){
oracle.jdbc.driver.OracleResultSet ors =
(oracle.jdbc.driver.OracleResultSet)result;
oracle.sql.CLOB clobtmp = (oracle.sql.CLOB) ors.getClob(1);
if(clobtmp==null || clobtmp.length()==0){
System.out.println(“======CLOB對象為空 “);
description = “”;
}else{
description=clobtmp.getSubString((long)1,(int)clobtmp.length());
System.out.println(“======字元串形式 “+description);
}
}
使用java語言操作,如何來實現MySQL中Blob欄位的存取
/**
* Title: BlobPros.java
* Project: test
* Description: 把圖片存入mysql中的blob欄位,並取出
* Call Module: mtools資料庫中的tmp表
* File: C:downloadsluozsh.jpg
* Copyright: Copyright (c) 2003-2003
* Company: uniware
* Create Date: 2002.12.5
* @Author: ChenQH
* @version 1.0 版本*
*
* Revision history
* Name Date Description
* —- —- ———–
* Chenqh 2003.12.5 對圖片進行存取
*
* note: 要把資料庫中的Blob欄位設為longblob
*
*/
//package com.uniware;
import java.io.*;
import java.util.*;
import java.sql.*;
public class BlobPros
{
private static final String URL = “jdbc:mysql://10.144.123.63:3306/mtools?user=windpassword=123useUnicode=true”;
private Connection conn = null;
private PreparedStatement pstmt = null;
private ResultSet rs = null;
private File file = null;
public BlobPros()
{
}
/**
* 向資料庫中插入一個新的BLOB對象(圖片)
* @param infile 要輸入的數據文件
* @throws java.lang.Exception
*/
public void blobInsert(String infile) throws Exception
{
FileInputStream fis = null;
try
{
Class.forName(“org.gjt.mm.mysql.Driver”).newInstance();
conn = DriverManager.getConnection(URL);
file = new File(infile);
fis = new FileInputStream(file);
//InputStream fis = new FileInputStream(infile);
pstmt = conn.prepareStatement(“insert into tmp(descs,pic) values(?,?)”);
pstmt.setString(1,file.getName()); //把傳過來的第一個參數設為文件名
//pstmt.setBinaryStream(2,fis,(int)file.length()); //這種方法原理上會丟數據,因為file.length()返回的是long型
pstmt.setBinaryStream(2,fis,fis.available()); //第二個參數為文件的內容
pstmt.executeUpdate();
}
catch(Exception ex)
{
System.out.println(“[blobInsert error : ]” + ex.toString());
}
finally
{
//關閉所打開的對像//
pstmt.close();
fis.close();
conn.close();
}
}
/**
* 從資料庫中讀出BLOB對象
* @param outfile 輸出的數據文件
* @param picID 要取的圖片在資料庫中的ID
* @throws java.lang.Exception
*/
public void blobRead(String outfile,int picID) throws Exception
{
FileOutputStream fos = null;
InputStream is = null;
byte[] Buffer = new byte[4096];
try
{
Class.forName(“org.gjt.mm.mysql.Driver”).newInstance();
conn = DriverManager.getConnection(URL);
pstmt = conn.prepareStatement(“select pic from tmp where id=?”);
pstmt.setInt(1,picID); //傳入要取的圖片的ID
rs = pstmt.executeQuery();
rs.next();
file = new File(outfile);
if(!file.exists())
{
file.createNewFile(); //如果文件不存在,則創建
}
fos = new FileOutputStream(file);
is = rs.getBinaryStream(“pic”);
int size = 0;
/* while(size != -1)
{
size = is.read(Buffer); //從資料庫中一段一段的讀出數據
//System.out.println(size);
if(size != -1) //-1表示讀到了文件末
fos.write(Buffer,0,size);
} */
while((size = is.read(Buffer)) != -1)
{
//System.out.println(size);
fos.write(Buffer,0,size);
}
}
catch(Exception e)
{
System.out.println(“[OutPutFile error : ]” + e.getMessage());
}
finally
{
//關閉用到的資源
fos.close();
rs.close();
pstmt.close();
conn.close();
}
}
public static void main(String[] args)
{
try
{
BlobPros blob = new BlobPros();
//blob.blobInsert(“C:Downloadsluozsh1.jpg”);
blob.blobRead(“c:/downloads/1.jpg”,47);
}
catch(Exception e)
{
System.out.println(“[Main func error: ]” + e.getMessage());
}
}
}
java怎樣創建一個blob對象
java向oracle寫入blob
public void doWriteInHis(String id, String XML) {
int flag = 0;
Connection conn = null;
PreparedStatement pstmt = null;
ResultSet rest = null;
StringBuffer insql = new StringBuffer();
insql.append(“insert into test (id,IN_XML) “);
insql.append(“values(?,empty_clob()) “);
StringBuffer sqlSelect = new StringBuffer();
sqlSelect.append(“SELECT IN_XML FROM test “);
sqlSelect.append(” WHERE id = ? for update”);
try {
conn = getConnection();
pstmt = conn.prepareStatement(insql.toString());
int index = 1;
pstmt.setString(index++, id);
flag = pstmt.executeUpdate();
pstmt.close();
if (flag 0) {
pstmt = conn.prepareStatement(sqlSelect.toString());
index = 1;
pstmt.setString(index++, seq);
conn.setAutoCommit(false);
rest = pstmt.executeQuery();
if (rest.next()) {
oracle.sql.CLOB clob = (oracle.sql.CLOB) rest.getClob(1);
Writer os = clob.getCharacterOutputStream();
os.write(XML);
os.flush();
os.close();
}
conn.commit();
conn.setAutoCommit(true);
}
} catch (Exception e) {
SysLog.writeLogs(“WriteHisDAOImpl”, GlobalParameters.ERROR,
“WriteHisDAOImpl–doWriteInHis()-2:” + e.getMessage());
} finally {
close(conn);
}
}
java中blob類型是什麼類型
blob是資料庫二進位對象的類型,圖片,文本之類的.
java沒有特定類,非要說的話,就是個超大的位元組數組~
java 關於blob類型問題
public void save(String vid,String title,String type,String user,String date,String context,String file) throws Exception
{
Connection conn = null;
Statement stmt = null;
ResultSet rs = null;
String sql = “insert into news(v_id,title,type,person,inputtime,context,attach_docid) values(‘”+vid+”‘,'”+title+”‘,'”+type+”‘,'”+user+”‘,'”+date+”‘,EMPTY_BLOB(),'”+file+”‘)”;
try {
DBJdbc dbjdbc = new DBJdbc();
conn = dbjdbc.getDBConnection();
conn.setAutoCommit(false);
stmt = conn.createStatement();
stmt.executeUpdate(sql);
String sql1 = “select context from news where v_id ='”+vid+”‘ for update”; // 使用”FOR UPDATE”得到表的寫鎖
rs = stmt.executeQuery(sql1);
if (rs.next()) {
BLOB blob = (BLOB) rs.getBlob(1); // 得到BLOB對象
OutputStream outout = blob.getBinaryOutputStream(); // 建立輸出流
InputStream in = new ByteArrayInputStream(strss.HTMLEncode(context).getBytes()); //字元串轉換為數據流
int size = blob.getBufferSize();
byte[] buffer = new byte[size]; // 建立緩衝區
int len;
while ((len = in.read(buffer)) != -1)
outout.write(buffer, 0, len);
in.close();
outout.close();
}
conn.commit();
stmt.close();
conn.close();
}catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}
希望能幫助到你
如何在java中讀取oracle blob
整個流程分為四步,連接oracle資料庫 – 讀取blob圖片欄位 – 對圖片進行縮放 -把圖片展示在jsp頁面上。
下面進行詳細描述:
1. java連接Oracle
註:資料庫是Oracle10g版本為10.2.0, 在資料庫中,圖片欄位類型為BLOB。
java中通常使用的是通過jdbc驅動來連接資料庫,oracle也不例外,因此必須下載一個Oracle驅動的jdbc需要去網上進行下載,名稱為 ojdbc14.jar。
下載地址為:
下載了驅動之後,可以使用驅動里提供的介面進行連接,具體代碼如下:
import java.sql.*;
import java.io.*;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.awt.image.AffineTransformOp;
import java.awt.geom.AffineTransform;
public class OracleQueryBean {
private final String oracleDriverName = “oracle.jdbc.driver.OracleDriver”;
private Connection myConnection = null;
/*圖片表名*/
private String strTabName;
/*圖片ID欄位名*/
private String strIDName;
/*圖片欄位名*/
private String strImgName;
/**
* 載入java連接Oracle的jdbc驅動
*/
public OracleQueryBean(){
try{
Class.forName(oracleDriverName);
}catch(ClassNotFoundException ex){
System.out.println(“載入jdbc驅動失敗,原因:” + ex.getMessage());
}
}
/**
* 獲取Oracle連接對象
* @return Connection
*/
public Connection getConnection(){
try{
//用戶名+密碼; 以下使用的Test就是Oracle里的表空間
//從配置文件中讀取資料庫信息
GetPara oGetPara = new GetPara();
String strIP = oGetPara.getPara(“serverip”);
String strPort = oGetPara.getPara(“port”);
String strDBName = oGetPara.getPara(“dbname”);
String strUser = oGetPara.getPara(“user”);
String strPassword = oGetPara.getPara(“password”);
this.strTabName = oGetPara.getPara(“tablename”);
this.strIDName = oGetPara.getPara(“imgidname”);
this.strImgName = oGetPara.getPara(“imgname”);
String oracleUrlToConnect =”jdbc:oracle:thin:@”+strIP+”:”+strPort+”:”+strDBName;
this.myConnection = DriverManager.getConnection(oracleUrlToConnect, strUser, strPassword);
}catch(Exception ex){
System.out.println(“Can not get connection:” + ex.getMessage());
System.out.println(“請檢測配置文件中的資料庫信息是否正確.” );
}
return this.myConnection;
}
}
2. 讀取blob欄位
在OracleQueryBean類中增加一個函數,來進行讀取,具體代碼如下:
/**
* 根據圖片在資料庫中的ID進行讀取
* @param strID圖片欄位ID
* @param w 需要縮到的寬度
* @param h 需要縮到高度
* @return
*/
public byte[] GetImgByteById(String strID, int w, int h){
//System.out.println(“Get img data which id is ” + nID);
if(myConnection == null)
this.getConnection();
byte[] data = null;
try {
Statement stmt = myConnection.createStatement();
ResultSet myResultSet = stmt.executeQuery(“select ” + this.strIDName + ” from ” + this.strTabName + ” where ” + this.strIDName + “=” + strID);
StringBuffer myStringBuffer = new StringBuffer();
if (myResultSet.next()) {
java.sql.Blob blob = myResultSet.getBlob(this.strImgName);
InputStream inStream = blob.getBinaryStream();
try {
long nLen = blob.length();
int nSize = (int) nLen;
//System.out.println(“img data size is :” + nSize);
data = new byte[nSize];
inStream.read(data);
inStream.close();
} catch (IOException e) {
System.out.println(“獲取圖片數據失敗,原因:” + e.getMessage());
}
data = ChangeImgSize(data, w, h);
}
System.out.println(myStringBuffer.toString());
myConnection.commit();
myConnection.close();
} catch (SQLException ex) {
System.out.println(ex.getMessage());
}
return data;
}
3. 縮放圖片
因為圖片的大小可能不一致,但是在頁面中輸出的大小需要統一,所以需要
在OracleQueryBean類中增加一個函數,來進行縮放,具體代碼如下:
/**
* 縮小或放大圖片
* @param data 圖片的byte數據
* @param w 需要縮到的寬度
* @param h 需要縮到高度
* @return 縮放後的圖片的byte數據
*/
private byte[] ChangeImgSize(byte[] data, int nw, int nh){
byte[] newdata = null;
try{
BufferedImage bis = ImageIO.read(new ByteArrayInputStream(data));
int w = bis.getWidth();
int h = bis.getHeight();
double sx = (double) nw / w;
double sy = (double) nh / h;
AffineTransform transform = new AffineTransform();
transform.setToScale(sx, sy);
AffineTransformOp ato = new AffineTransformOp(transform, null);
//原始顏色
BufferedImage bid = new BufferedImage(nw, nh, BufferedImage.TYPE_3BYTE_BGR);
ato.filter(bis, bid);
//轉換成byte位元組
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ImageIO.write(bid, “jpeg”, baos);
newdata = baos.toByteArray();
}catch(IOException e){
e.printStackTrace();
}
return newdata;
}
4. 展示在頁面
頁面使用OracleQueryBean來根據用戶提供的圖片id進行查詢,在讀取並進行縮放後,通過jsp頁面進行展示,具體代碼如下:
%@ page language=”java” contentType=”text/html;;charset=gbk” %
jsp:useBean id=”OrcleQuery” scope=”page” class=”HLFtiDemo.OracleQueryBean” /
%
response.setContentType(“image/jpeg”);
//圖片在資料庫中的 ID
String strID = request.getParameter(“id”);
//要縮略或放大圖片的寬度
String strWidth = request.getParameter(“w”);
//要縮略或放大圖片的高度
String strHeight = request.getParameter(“h”);
byte[] data = null;
if(strID != null){
int nWith = Integer.parseInt(strWidth);
int nHeight = Integer.parseInt(strHeight);
//獲取圖片的byte數據
data = OrcleQuery.GetImgByteById(strID, nWith, nHeight);
ServletOutputStream op = response.getOutputStream();
op.write(data, 0, data.length);
op.close();
op = null;
response.flushBuffer();
//清除輸出流,防止釋放時被捕獲異常
out.clear();
out = pageContext.pushBody();
}
%
5. OracleQueryBean查詢類的整體代碼
OracleQueryBean.java文件代碼如下所示:
import java.sql.*;
import java.io.*;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.awt.image.AffineTransformOp;
import java.awt.geom.AffineTransform;
public class OracleQueryBean {
private final String oracleDriverName = “oracle.jdbc.driver.OracleDriver”;
private Connection myConnection = null;
/*圖片表名*/
private String strTabName;
/*圖片ID欄位名*/
private String strIDName;
/*圖片欄位名*/
private String strImgName;
/**
* 載入java連接Oracle的jdbc驅動
*/
public OracleQueryBean(){
try{
Class.forName(oracleDriverName);
}catch(ClassNotFoundException ex){
System.out.println(“載入jdbc驅動失敗,原因:” + ex.getMessage());
}
}
/**
* 獲取Oracle連接對象
* @return Connection
*/
public Connection getConnection(){
try{
//用戶名+密碼; 以下使用的Test就是Oracle里的表空間
//從配置文件中讀取資料庫信息
GetPara oGetPara = new GetPara();
這文章確實寫的不錯,你可以看原文
原創文章,作者:ABZK,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/132080.html