CLOB插入到Oracle数据库(Insert CLOB into Oracle database)

2019-06-24 17:34发布

我的问题是:你如何避开ORA-01704: string literal too long插入(或在做任何事情的查询)与时错误CLOB S'

我想有这样的查询:

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的是在一个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;
}

Answer 1:

你是做它的方式复杂。

使用在你的列表中的每个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()调用和读者的创作是没有必要的要么。 一个简单setString(1, query)将最有可能正常工作。



Answer 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();
}


Answer 3:

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(); 
        } 
    } 
} 


Answer 4:

从甲骨文文件

你必须牢记大数据输入模式下自动切换。 有三种输入模式如下:直接绑定,绑定流和LOB绑定。

对于PL / SQL语句

的setBytes和将优先考虑setBinary流方法使用直接用于小于32767个字节的数据绑定。

的setBytes和的setBinaryStream方法使用LOB超过32766个字节的数据绑定。

该了setString,的setCharacterStream,并调用setAsciiStream方法,使用直接用于比数据库中的字符集32767个字节较小的数据绑定。

的了setString,的setCharacterStream,并调用setAsciiStream方法使用LOB为比数据库中的字符集32766个字节的数据绑定。

的setBytesForBlob和setStringForClob方法,存在于oracle.jdbc.OraclePreparedStatement接口,使用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();
    }
  }


Answer 5:

我,我喜欢从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在该版本未知的原因,所以我不得不这样做的Double-Take(我花了好长时间才弄清楚,所以我在这里分享...)

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,感谢。



Answer 6:

检查出一些CLOB相关样品github上 。



文章来源: Insert CLOB into Oracle database