【问题标题】:Groovy sql to byteGroovy sql到字节
【发布时间】:2015-02-24 16:11:03
【问题描述】:

我必须获取一个存储在 postgres 数据库中的文档并将其放入一个字节数组中。

在 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 中获得与在 java 中相同的结果,从我的 sql 结果集中获得一个 byte[] 变量?

提前致谢。

【问题讨论】:

    标签: postgresql groovy bytearray


    【解决方案1】:

    最后这很容易,但不知道 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[] 表示。

    【讨论】: