我有一个字符串“stringData”,我想将其转换为 Clob,你能帮我吗?
我已经尝试过:
Clob clob = new SerialClob(stringData.toCharArray());
但它给出了错误。
最佳答案
因此,未处理的异常
问题并不直接与.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的接受答案中也有讨论。
关于java - 将字符串转换为 Clob,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56584397/