在 Clob 中转换字符串

Convert a String in Clob

我有一个字符串 "stringData",我想将它转换成 Clob,你能帮我吗?

我试过:

Clob clob = new SerialClob(stringData.toCharArray());

但它给出了错误。

所以 Unhandled Exception 的问题与 .toCharArray()SerialClob 没有直接的问题。相反,问题是检查异常必须被捕获或声明为方法的一部分。

所以(示例 1):

try {
  ...
  Clob clob = new SerialClob(stringData.toCharArray());
  ...
}
catch (SQLException e) {
  // do handle better than this, however
  e.printStackTrace();
}

或(示例 2):

/**
   @throws SQLException If there is an issue with creating the data, or 
                        inserting into the DB
*/
private void storeData(StringData stringData) throws SQLException
{
  ...
  Clob clob = new SerialClob(stringData.toCharArray());
  ...
 }

当然,对于后者,一些其他方法将需要捕获 SQLException。

本质上,SQLException 是一个 CheckedException。来自 JLS 11.2

The Java programming language requires that a program contains handlers for checked exceptions which can result from execution of a method or constructor. For each checked exception which is a possible result, the throws clause for the method (§8.4.6) or constructor (§8.8.5) must mention the class of that exception or one of the superclasses of the class of that exception (§11.2.3).

因此,要么必须捕获 SQLException(示例 1),要么将其添加到方法的 throws 子句中(示例 2)。

您收到编译时问题的原因在 JLS, 11.2.3 Exception Checking:

It is a compile-time error if a method or constructor body can throw some exception class E when E is a checked exception class and E is not a subclass of some class declared in the throws clause of the method or constructor.

接受的答案中也有讨论this question about Checked vs. Unchecked Exceptions