4

我的问题是:ORA-01704: string literal too long使用 s插入(或在查询中执行任何操作)时如何解决错误CLOB

我想要这样的查询:

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: string literal too long回来了。这很明显,但是我如何插入 clob(或使用 clob 执行任何语句)?

我试过看这个问题,但我认为它没有我想要的东西。我拥有的 clob 在 a 中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;
}
4

6 回答 6

8

你让它变得复杂。

为列表中的每个 clob 使用 PreparedStatement 和 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();

没有转义字符串,没有文字长度的问题,不需要创建临时 clob。而且很可能与使用单个 INSERT ALL 语句一样快。

如果您使用的是当前驱动程序(> 10.2),那么我认为 setCharacterStream() 调用和 Reader 的创建也没有必要。一个简单的setString(1, query)也很可能会起作用。

于 2012-05-23T22:11:48.187 回答
2

您需要使用绑定变量,而不是使用字符串连接构建 SQL 语句。从安全性、性能和健壮性的角度来看,这也将是有益的,因为它将降低 SQL 注入攻击的风险,减少 Oracle 必须花费在 SQL 语句的硬解析上的时间量,并消除潜在的 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();
}
于 2012-05-23T20:52:51.670 回答
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(); 
        } 
    } 
} 
于 2012-10-06T17:04:35.957 回答
2

来自Oracle 文档

您必须牢记以下大数据输入模式的自动切换。输入方式有以下三种:直接绑定、流绑定、LOB绑定。

对于 PL/SQL 语句

setBytes 和 setBinary 流方法对小于 32767 字节的数据使用直接绑定。

setBytes 和 setBinaryStream 方法对大于 32766 字节的数据使用 LOB 绑定。

setString、setCharacterStream 和 setAsciiStream 方法对数据库字符集中小于 32767 字节的数据使用直接绑定。

setString、setCharacterStream 和 setAsciiStream 方法对数据库字符集中大于 32766 字节的数据使用 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();
    }
  }
于 2012-12-14T20:57:26.937 回答
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,谢谢。

于 2018-10-24T12:58:26.333 回答
0

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

于 2018-11-02T23:42:00.690 回答