Java如何从数据库读取CLOB数据?
package org.nhooo.example.jdbc;import java.io.File;
import java.io.FileWriter;
import java.io.Reader;
import java.sql.*;
public class ClobReadDemo {
private static final String URL = "jdbc:mysql://localhost/nhooo";
private static final String USERNAME = "root";
private static final String PASSWORD = "";
public static void main(String[] args) {
try (Connection conn =
DriverManager.getConnection(URL, USERNAME, PASSWORD)) {
String sql = "SELECT book_isbn, data FROM book_excerpts";
PreparedStatement stmt = conn.prepareStatement(sql);
ResultSet resultSet = stmt.executeQuery();
while (resultSet.next()) {
String bookIsbn = resultSet.getString("book_isbn");
// 获取我们的CLOB文件的字符流
Reader reader = resultSet.getCharacterStream("data");
File file = new File(bookIsbn + ".txt");
try (FileWriter writer = new FileWriter(file)) {
char[] buffer = new char[1];
while (reader.read(buffer) > 0) {
writer.write(buffer);
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
book_excerpts表的结构。
CREATE TABLE `book_excerpts` (`id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
`book_isbn` varchar(50) NOT NULL,
`description` varchar(255) NOT NULL,
`data` longtext,
PRIMARY KEY (`id`),
KEY `book_isbn` (`book_isbn`),
CONSTRAINT `book_excerpts_ibfk_1` FOREIGN KEY (`book_isbn`) REFERENCES `books` (`isbn`)
) ENGINE=InnoDB;
Maven依赖
<!-- https://search.maven.org/remotecontent?filepath=mysql/mysql-connector-java/8.0.17/mysql-connector-java-8.0.17.jar --><dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.17</version>
</dependency>
以上是 Java如何从数据库读取CLOB数据? 的全部内容, 来源链接: utcz.com/z/321423.html