> Java > java지도 시간 > 본문

Java에서 CLOB 유형을 문자열로 변환하는 방법은 무엇입니까?

王林
풀어 주다: 2023-09-11 18:09:02
앞으로
1668명이 탐색했습니다.

在Java中如何将CLOB类型转换为字符串?

CLOB는 일반적으로 Character Large Object의 약자이며 SQL Clob은 대량의 텍스트 데이터를 저장하는 데 사용되는 내장 데이터 유형입니다. 이 데이터 유형을 사용하면 최대 2,147,483,647자의 데이터를 저장할 수 있습니다.

JDBC API의 java.sql.Clob 인터페이스는 CLOB 데이터 유형을 나타냅니다. JDBC의 Clob 객체는 SQL 위치 지정자를 사용하여 구현되므로 SQL CLOB(데이터가 아님)에 대한 논리적 포인터를 보유합니다.

MySQL 데이터베이스는 TINYTEXT, TEXT, MEDIUMTEXT 및 LONGTEXT라는 네 가지 변수를 사용하여 이 데이터 유형을 지원합니다.

CLOB 데이터 유형을 문자열로 변환합니다.

  • PreparedStatement 인터페이스의 getClob() 또는 getCharacterStream() 메소드를 사용하여 테이블에서 Clob 값을 검색합니다.
Reader r = clob.getCharacterStream();
로그인 후 복사
  • 는 검색된 문자 스트림에서 각 문자를 하나씩 읽고 이를 StringBuilder 또는 StringBuffer에 추가합니다.
int j = 0;
StringBuffer buffer = new StringBuffer();
int ch;
while ((ch = r.read())!=-1) {
   buffer.append(""+(char)ch);
}
System.out.println(buffer.toString());
j++;
로그인 후 복사
  • 마지막으로 얻은 문자열을 표시하거나 저장합니다.
System.out.println(buffer.toString());
로그인 후 복사

Example

다음 쿼리를 사용하여 MySQL 데이터베이스에 technologies_data라는 테이블을 생성해 보겠습니다. -

CREATE TABLE Technologies (Name VARCHAR(255), Type VARCHAR(255), Article LONGTEXT);
로그인 후 복사

table Article의 세 번째 열에는 CLOB 유형의 데이터가 저장됩니다.

다음 JDBC 프로그램은 처음에 텍스트 파일(해당 내용)을 저장하는 Technologies_data 테이블의 Article 열(CLOB)에 5개의 레코드를 삽입합니다.

그런 다음 테이블의 기록을 검색하고 기사 이름과 내용을 표시합니다. 여기서는 검색된 CLOB 데이터를 문자열로 변환하여 표시하려고 합니다.

import java.io.FileReader;
import java.io.Reader;
import java.sql.Clob;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;
public class ClobToString {
   public static void main(String args[]) throws Exception {
      //Registering the Driver
      DriverManager.registerDriver(new com.mysql.jdbc.Driver());
      //Getting the connection
      String mysqlUrl = "jdbc:mysql://localhost/sampledatabase";
      Connection con = DriverManager.getConnection(mysqlUrl, "root", "password");
      System.out.println("Connection established......");
      //Creating a Statement object
      Statement stmt = con.createStatement();
      //Inserting values
      String query = "INSERT INTO Technologies_data VALUES (?, ?, ?)";
      PreparedStatement pstmt = con.prepareStatement(query);
      pstmt.setString(1, "JavaFX");
      pstmt.setString(2, "Java Library");
      FileReader reader = new FileReader("E:\images\javafx_contents.txt");
      pstmt.setClob(3, reader);
      pstmt.execute();
      pstmt.setString(1, "CoffeeScript");
      pstmt.setString(2, "Scripting Language");
      reader = new FileReader("E:\images\coffeescript_contents.txt");
      pstmt.setClob(3, reader);
      pstmt.execute();
      pstmt.setString(1, "Cassandra");
      pstmt.setString(2, "NoSQL Database");
      reader = new FileReader("E:\images\cassandra_contents.txt");
      pstmt.setClob(3, reader);
      pstmt.execute();
      //Retrieving the data
      ResultSet rs = stmt.executeQuery("select * from Technologies_data");
      System.out.println("Contents of the table are: ");
      while(rs.next()) {
         System.out.println("Article: "+rs.getString("Name"));
         Clob clob = rs.getClob("Article");
         Reader r = clob.getCharacterStream();
         StringBuffer buffer = new StringBuffer();
         int ch;
         while ((ch = r.read())!=-1) {
            buffer.append(""+(char)ch);
         }
         System.out.println("Contents: "+buffer.toString());
         System.out.println(" ");
      }
   }
}
로그인 후 복사

출력

Connection established......
Contents of the table are:
Article: JavaFX
Contents: JavaFX is a Java library using which you can develop Rich Internet Applications. By using Java technology, these applications have a browser penetration rate of 76%.
Article: CoffeeScript
Contents: CoffeeScript is a lightweight language based on Ruby and Python which transcompiles (compiles from one source language to another) into JavaScript. It provides better syntax avoiding the quirky parts of JavaScript, still retaining the flexibility and beauty of the language.
Article: Cassandra
Contents: Apache Cassandra is a highly scalable, high-performance distributed database designed to handle large amounts of data across many commodity servers,
providing high availability with no single point of failure. It is a type of NoSQL database. Let us first understand what a NoSQL database does.
로그인 후 복사

위 내용은 Java에서 CLOB 유형을 문자열로 변환하는 방법은 무엇입니까?의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

원천:tutorialspoint.com
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿
회사 소개 부인 성명 Sitemap
PHP 중국어 웹사이트:공공복지 온라인 PHP 교육,PHP 학습자의 빠른 성장을 도와주세요!