将CLOB插入Oracle数据库

4

我的问题是:当插入(或在查询中进行任何操作)CLOB时,如何解决ORA-01704:字符串文字太长错误?

我希望有一个像这样的查询:

INSERT ALL
   INTO mytable VALUES ('clob1')
   INTO mytable VALUES ('clob2') --some of these clobs are more than 4000 characters...
   INTO mytable VALUES ('clob3')
SELECT * FROM dual;

当我使用实际值时,我收到了ORA-01704:字符串文字太长的反馈。这很明显,但是我该如何插入clobs(或使用clob执行任何语句)?
我尝试查看这个问题,但我不认为它有我要找的内容。我拥有的clobs在一个List<String>中,我遍历它们以创建语句。我的代码如下:
private void insertQueries(String tempTableName) throws FileNotFoundException, DataException, SQLException, IOException {
String preQuery = "  into " + tempTableName + " values ('";
String postQuery = "')" + StringHelper.newline;
StringBuilder inserts = new StringBuilder("insert all" + StringHelper.newline);
List<String> readQueries = getDomoQueries();
for (String query : readQueries) {
  inserts.append(preQuery).append(query).append(postQuery);
}
inserts.append("select * from dual;");

DatabaseController.getInstance().executeQuery(databaseConnectionURL, inserts.toString());

}

public ResultSet executeQuery(String connection, String query) throws DataException, SQLException {
  Connection conn = ConnectionPool.getInstance().get(connection);
  Statement stmt = conn.createStatement();
  ResultSet rs = stmt.executeQuery(query);
  conn.commit();
  ConnectionPool.getInstance().release(conn);
  return rs;
}

1
你有没有尝试使用PreparedStatement及其setClob()方法,而不是动态SQL和构建带有字符串字面量的插入语句? - QuantumMechanic
6个回答

8
你正在让它变得过于复杂了。
使用PreparedStatement并为列表中的每个clob添加addBatch():
String sql = "insert  into " + tempTableName + " values (?)";
PreparedStatement stmt = connection.prepareStatement(sql);
for (String query : readQueries) {
  stmt.setCharacterStream(1, new StringReader(query), query.lenght());
  stmt.addBatch();
}
stmt.exececuteBatch();

不需要烦恼于转义字符串,不必担心字面量的长度,也不需要创建临时clobs。而且很可能与使用单个INSERT ALL语句的速度相同。

如果您使用的是当前的驱动程序(> 10.2),那么我认为setCharacterStream()调用和Reader的创建也不是必需的。简单的setString(1, query)可能也能正常工作。


2
您需要使用绑定变量而不是使用字符串拼接构建SQL语句。这将从安全性、性能和健壮性方面带来好处,因为它将减少SQL注入攻击的风险,减少Oracle执行SQL语句所需的解析时间,并消除字符串中可能导致生成无效SQL语句的特殊字符(例如单引号)的潜在问题。
我认为您需要类似以下的内容:
private void insertQueries(String tempTableName) throws FileNotFoundException, DataException, SQLException, IOException {
  String preQuery = "  into " + tempTableName + " values (?)" + StringHelper.newline;
  StringBuilder inserts = new StringBuilder("insert all" + StringHelper.newline);
  List<String> readQueries = getDomoQueries();
  for (String query : readQueries) {
    inserts.append(preQuery);
  }
  inserts.append("select * from dual");

  Connection conn = ConnectionPool.getInstance().get(connection);
  PreparedStatement pstmt = conn.prepareStatement(
        inserts);
  int i = 1;
  for (String query : readQueries) {
    Clob clob = CLOB.createTemporary(conn, false, oracle.sql.CLOB.DURATION_SESSION);
    clob.setString(i, query);
    pstmt.setClob(i, clob);
    i = i + 1;
  }
  pstmt.executeUpdate();
}

我认为这应该可以工作,除了 setClob 方法需要一个 clob 而不是一个字符串。在另一个问题中,它展示了如何创建 clob:oracle.sql.CLOB.createTemporary(connection, false, oracle.sql.CLOB.DURATION_SESSION); 这样正确吗? - kentcdodds
@kentcdodds - 我相信是这样的(我现在没有我的Java开发环境来测试) - Justin Cave
您还可以对Oracle CLOB列执行setString()操作。Oracle JDBC驱动程序足够智能,可以执行转换。 - GriffeyDog
这个工作很好(我想)。我得到了一个 ORA-00911: invalid character 的错误,这并不是什么意外。我已经找过了,有没有什么简单的方法可以从 PreparedStatement 中获取查询语句,以便我可以看到问题出在哪里? - kentcdodds
@JustinCave,我刚刚编辑了你的Clob答案,但我不确定是要使用clob.setString(i, query);还是clob.setString(1, query);... - kentcdodds
显示剩余3条评论

2

BLOB(二进制大对象)和 CLOB(字符大对象)是特殊的数据类型,可以以对象或文本形式保存大块数据。Blob 和 Clob 对象将对象数据作为流持久化到数据库中。

以下是示例代码:

public class TestDB { 
    public static void main(String[] args) { 
        try { 
            /** Loading the driver */ 
            Class.forName("com.oracle.jdbc.Driver"); 

            /** Getting Connection */ 
            Connection con = DriverManager.getConnection("Driver URL","test","test"); 

            PreparedStatement pstmt = con.prepareStatement("insert into Emp(id,name,description)values(?,?,?)"); 
            pstmt.setInt(1,5); 
            pstmt.setString(2,"Das"); 

            // Create a big CLOB value...AND inserting as a CLOB 
            StringBuffer sb = new StringBuffer(400000); 

            sb.append("This is the Example of CLOB .."); 
            String clobValue = sb.toString(); 

            pstmt.setString(3, clobValue); 
            int i = pstmt.executeUpdate(); 
            System.out.println("Done Inserted"); 
            pstmt.close(); 
            con.close(); 

            // Retrive CLOB values 
            Connection con = DriverManager.getConnection("Driver URL","test","test"); 
            PreparedStatement pstmt = con.prepareStatement("select * from Emp where id=5"); 
            ResultSet rs = pstmt.executeQuery(); 
            Reader instream = null; 

            int chunkSize; 
            if (rs.next()) { 
                String name = rs.getString("name"); 
                java.sql.Clob clob = result.getClob("description") 
                StringBuffer sb1 = new StringBuffer(); 

                chunkSize = ((oracle.sql.CLOB)clob).getChunkSize(); 
                instream = clob.getCharacterStream(); 
                BufferedReader in = new BufferedReader(instream); 
                String line = null; 
                while ((line = in.readLine()) != null) { 
                    sb1.append(line); 
                } 

                if (in != null) { 
                    in.close(); 
                } 

                // this is the clob data converted into string
                String clobdata = sb1.toString();  
            } 
        } catch (Exception e) { 
            e.printStackTrace(); 
        } 
    } 
} 

1
感谢您提供回复。下次请使用合理的缩进方案格式化您的代码。我会为您编辑帖子。 (提示:如果您的代码不仅功能强大而且美观,您将获得更多的赞成票。) - bohney

2

以下内容来自Oracle文档

在处理大数据时,需要注意输入模式的自动切换。有三种输入模式如下:直接绑定(Direct binding)、流绑定(Stream binding)和LOB绑定。

对于PL/SQL语句:

当数据小于32767字节时,setBytes和setBinary stream方法使用直接绑定。

当数据大于32766字节时,setBytes和setBinaryStream方法使用LOB绑定。

当存储在数据库字符集中的数据小于32767字节时,setString、setCharacterStream和setAsciiStream方法使用直接绑定。

当存储在数据库字符集中的数据大于32766字节时,setString、setCharacterStream和setAsciiStream方法使用LOB绑定。

oracle.jdbc.OraclePreparedStatement接口中的setBytesForBlob和setStringForClob方法使用LOB绑定用于任何数据大小。

以下是将文件内容放入PLSQL过程的输入CLOB参数的示例:

  public int fileToClob( FileItem uploadFileItem ) throws SQLException, IOException
  {
    //for using stmt.setStringForClob method, turn the file to a big String 
    FileItem item = uploadFileItem;
    InputStream inputStream = item.getInputStream();
    InputStreamReader inputStreamReader = new InputStreamReader( inputStream ); 
    BufferedReader bufferedReader = new BufferedReader( inputStreamReader );    
    StringBuffer stringBuffer = new StringBuffer();
    String line = null;

    while((line = bufferedReader.readLine()) != null) {  //Read till end
        stringBuffer.append(line);
        stringBuffer.append("\n");
    }

    String fileString = stringBuffer.toString();

    bufferedReader.close();         
    inputStreamReader.close();
    inputStream.close();
    item.delete();

    OracleCallableStatement stmt;

    String strFunction = "{ call p_file_to_clob( p_in_clob => ? )}";  

    stmt= (OracleCallableStatement)conn.prepareCall(strFunction);    

    try{    
      SasUtility servletUtility = sas.SasUtility.getInstance();

      stmt.setStringForClob(1, fileString );

      stmt.execute();

    } finally {      
      stmt.close();
    }
  }

0

我喜欢使用java.sql.*包中的类,而不是oracle.*的东西。对我来说,简单的方法更好。

Connection con = ...;
try (PreparedStatement pst = con.prepareStatement(
     "insert into tbl (other_fld, clob_fld) values (?,?)", new String[]{"tbl_id"});
     ) {
        Clob clob = con.createClob();
        readIntoClob(clob, inputStream);
        pst.setString(1, "other");
        pst.setClob(2, clob);
        pst.executeUpdate();
        try (ResultSet rst = pst.getGeneratedKeys()) {
            if (rst == null || !rst.next()) {
                throw new Exception("error with getting auto-generated key");
            }
            id = rst.getBigDecimal(1);
        }  

在测试时工作正常(使用当前的Tomcat和JDBC),但在投入生产环境时(由于某些愚蠢的原因被困在Tomcat6中),出现了问题。con.createClob() 在那个版本中返回 null,原因不明,所以我不得不做这个双重检查(花费了我很长时间才弄清楚,所以在这里分享一下...)

try (PreparedStatement pst = con.prepareStatement(
         "insert into tbl (other_fld) values (?)", new String[]{"tbl_id"});
     PreparedStatement getClob= con.prepareStatement(
         "select clob_fld from tbl where tbl_id = ? for update");
     ) {
        Clob clob = con.createClob();
        readIntoClob(clob, inputStream);
        pst.setString(1, "other");
        pst.executeUpdate();
        try (ResultSet rst = pst.getGeneratedKeys()) {
            if (rst == null || !rst.next()) {
                throw new Exception("error with getting auto-generated key");
            }
            id = rst.getBigDecimal(1);
        }  

        //  fetch back fresh record, with the Clob
        getClob.setBigDecimal(1, id);
        getClob.execute();
        try (ResultSet rst = getClob.getResultSet()) {
            if (rst == null || !rst.next()) {
                throw new Exception("error with fetching back clob");
            }
            Clob c = rst.getClob(1);
            // Fill in data
            readIntoClob(c, stream);
            // that's all 
        }

    } catch (SQLException) {
       ...
    }

为了完整性,此处是

// Read data from an input stream and insert it in to the clob column
private static void readIntoClob(Clob clob, InputStream stream) {
    try (BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(stream))) {
        char[] buffer = new char[CHUNK_BUFFER_SIZE];
        int charsRead;
        try (Writer wr = clob.setCharacterStream(1L)) {
            // Loop for reading of chunk of data and then write into the clob.
            while ((charsRead = bufferedReader.read(buffer)) != -1) {
                wr.write(buffer, 0, charsRead);
            }
        } catch (SQLException | IOException ex) {
            ...
        }

    }
}

这段代码来自 SO 的其他地方,谢谢。


0

Github 上查看一些与 CLOB 相关的示例。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接