2015-02-24 104 views
0

我必須得到一個存儲在postgres數據庫中的文檔,並將其放入一個字節數組中。Groovy sql to byte

在Java中,這只是正常

PreparedStatement ps = conn1.prepareStatement("SELECT document FROM documents WHERE documentname = ?"); 
ps.setString(1, "dingbatdocument.docx"); 
ResultSet rs = ps.executeQuery(); 
while (rs.next()) { 
    byte[] documentBytes = rs.getBytes(1); 
} 

,但我不得不使用Groovy此代碼一竅不通如何做到這一點,到目前爲止,我已經試過這

def newSpelling = "dingbatdocument.docx"; 
def val = sql.execute("SELECT document FROM documents WHERE documentname = ?", [newSpelling]) as byte[]; 

和得到這個錯誤:

Caused by: org.codehaus.groovy.runtime.typehandling.GroovyCastException: Cannot cast object 'true' with class 'java.lang.Boolean' to class 'byte' 
at korg.codehaus.groovy.runtime.typehandling.DefaultTypeTransformation.castToNumber(DefaultTypeTransformation.java:146) 

這對我來說,它試圖資產,它已經工作,而不是給我一個第二實際字節數組,

def newSpelling = "dingbatdocument.docx"; 
byte[] val = sql.execute("SELECT document FROM documents WHERE documentname = ?", [newSpelling]); 

,並得到這個錯誤:

Groovy script throws an exception of type class org.postgresql.util.PSQLException with message = This ResultSet is closed. 

最後這一點:

def reqdColName = "document"; 
    def reqdDocument = "dingbatdocument.docx"; 
    def query1 = "SELECT $reqdColName FROM documents WHERE documentname = '$reqdDocument'"; 
    def documentBytes = conn1.executeQuery(query1).getArray(reqdColName); 

這也給了我

Groovy script throws an exception of type class org.postgresql.util.PSQLException with message = This ResultSet is closed. 

所以我的問題是如何在groovy中得到與我在sql結果集中的java [byte]變量相同的結果?

在此先感謝。

回答

0

最後它很容易,但不知道Groovy是不同的。這裏是我如何做到底,

def reqdColName = "document"; 
    def reqdDocument = "documentName.docx"; 
    def query1 = "SELECT * FROM documents WHERE documentname = '$reqdDocument'"; 


    byte[] myData; 
    conn1.eachRow(query1){ 
     row ->  
     if(debug){logger.severe(dI+thisTrace+"myData \n" 
     +"\t"+row.documentid+"\n" 
     +"\t"+row.documentname 
     +"\t"+row.versionmajor +"\n" 
     +"\t"+row.versionminor +"\n" 
     +"\t"+row.versionmini +"\n" 
     +"\t"+row.uploader +"\n" 
     +"\t"+row.approver +"\n" 
     +"\t"+row.uploaddate +"\n" 
     +"\t"+row.approvaldate +"\n" 
//  +"\t"+row.document+"\n" 
     );} 
     myData = row.document 
    } 

myData是我需要的文檔的byte []表示。