java - 将字符串转换为 Clob

标签 java spring string clob

我有一个字符串“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/

相关文章:

java - 如何在 spring mvc 应用程序中向数据库添加重复用户名时处理异常

c# - 如何将文本文件转换为 XML

c++ - GNU STL 字符串 : is copy-on-write involved here?

java - 如何将从控制台添加的字符串中的元素添加到java中的列表中

java - 在 IntelliJ 中密封 jar 文件

java - 以最大语言环境为开发人员定位的API的I18n/L10n

java - 我想使用类中的方法设置和获取实例属性

java - WebSocket 服务器 (Java) 无法读取但发送到 C# (Unity) 客户端

java - org.springframework.beans.factory.NoSuchBeanDefinitionException : No qualifying bean of type [org. springframework.data.hadoop.hive.HiveOperations]

java - Spring 无法在 Controller 中 Autowiring 存储库