SQL Server - Query varbinary data to convert to file by Java OutputStream

在這個例子之中,主要是將原本INSERT進TABLE COLUMN內的varbinary格式資料(檔案)讀

取出來之後,準備轉換回原來的檔案,以此達到檔案存進TABLE COLUMN及讀取出來使用

的目的。

SQL語法使用環境為:SQL Server 2008 R2

Table Schema 如下:
CREATE TABLE DocSave
(
    Id int,
    Name varchar(50) ,
    Ext varchar(10),
    RawData varbinary(max)
)

再來是,INSERT資料進TABLE內,語法如下:
INSERT INTO dbo.DocSave (Id, Name, Ext, RawData)
SELECT '1' ,'example','.doc', BulkColumn FROM Openrowset( Bulk 'C:\example.doc', Single_Blob) as doc;


OPENROWSET透過BULK來讀取檔案資料,並且設定參數為SINGLE_BLOB,將資料存成

varbinary(max) 類型的單一資料列。相關參考文件請見官網

接著將資料QUERY出來後,透過Java將檔案資料做OutputStream to File

相關程式碼如下:
String driver = "com.microsoft.sqlserver.jdbc.SQLServerDriver";
String url = "jdbc:sqlserver://localhost:1433;DatabaseName=TestTable";
String user = "sa";
String password = "123";
Connection m_conn = null;
OutputStream outputStream = null;
InputStream rawData = null;

try{
  Class.forName(driver);
  m_conn = DriverManager.getConnection(url, user, password);
  PreparedStatement getDoc = m_conn.prepareStatement("select * from DocSave");
  ResultSet rs = getDoc.executeQuery();
   
  int read = 0;
  while(rs.next()){
    outputStream = new FileOutputStream(new File("C://temp"+rs.getString("Ext")));
    rawData = rs.getAsciiStream("RawData");
    byte[] buffer = new byte[1024];
    while((read = rawData.read(buffer)) != -1){
        outputStream.write(buffer, 0, read);
    }
    outputStream.close();
    outputStream = null;
    rawData.close();
    rawData = null;
  }
} catch(Exception e){
    e.printStackTrace();
} finally{
  try {
      if(readBinary != null)readBinary.close();
      if(outputStream != null)outputStream.close();
      m_conn.close();
  } catch (SQLException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
  }
}



留言