큰 바이너리 객체 인 Blob (이진 큰 물체)은 이진 파일을 저장할 수있는 컨테이너입니다. 컴퓨터에서 Blob은 종종 이진 파일을 저장하기 위해 데이터베이스에 사용되는 필드 유형입니다. 블로브는 큰 파일입니다. 전형적인 멍청이는 그림 또는 사운드 파일입니다. 크기로 인해 특별한 방식으로 처리되어야합니다 (예 : 데이터베이스에 업로드, 다운로드 또는 저장).
1. 기본 개념
실제 개발에서 때때로 스토리지를 위해 대형 텍스트 또는 이진 데이터를 직접 저장하기 위해 프로그램을 사용해야합니다.
MySQL의 경우 얼룩 만 있지만 클로브는 없습니다. MySQL은 텍스트를 사용하여 큰 텍스트를 저장하고 텍스트와 블로브는 다음과 같이 나뉩니다.
TinyText, 텍스트, mediumtext 및 longtext
작은 블로브, 얼룩, 중간형 및 장 블로브
2. 테스트 환경 구축
2.1. 테스트 프로젝트 구조가 구축되었습니다
그림과 같이 :
2.2. db.properties 구성 파일을 쓰십시오
드라이버 = com.mysql.jdbc.driverUrl = jdbc : mysql : // localhost : 3306/jdbcstudyusername = rootpassword = xdp
2.3. jdbcutils 도구 클래스를 작성하십시오
ME.gacl.utils; import java.io.inputStream; import java.sql.connection; import java.sql.drivermanager; import java.sql.resultset; import java.sql.sqlexception; import java.sql.statement; problic java.util.properties; provals jdbcuts jdbcut jdbcutile jdbcutile. 문자열 드라이버 = null; 개인 정적 문자열 URL = NULL; 개인 정적 문자열 username = null; 개인 정적 문자열 비밀번호 = null; static {try {// db.properties 파일 inputStream in = jdbcutils.class.getClassLoader (). getResourceAsStream ( "db.properties")에서 데이터베이스 연결 정보를 읽습니다. 속성 proper = new Properties (); prop.load (in); // 데이터베이스 연결 가져옵니다 Driver = prop.getProperty ( "Driver"); // 데이터베이스 연결 URL 주소 URL = prop.getProperty ( "url"); // 데이터베이스 연결을 가져옵니다. 사용자 이름 username = prop.getProperty ( "username"); // 데이터베이스 연결 가져 오기 암호 비밀번호 = prop.GetProperty ( "Password"); // 데이터베이스 드라이버 클래스를로드합니다 .forname (드라이버); } catch (예외 e) {새로운 예외를 던지십시오. }} / *** @method : getConnection* @description : 데이터베이스 연결 객체를 가져옵니다. } / ** * @method : release * @description : release resources, * 릴리스 할 리소스는 연결 데이터베이스 연결 객체, SQL 명령을 실행할 책임이있는 명령문 개체 및 쿼리 결과를 저장하는 resultSet 객체 * @Anthor : @param conn * @param st * @param rs * / public static void (Connection, restet, rs) {// 쿼리 결과를 저장하는 resultset 객체를 닫으십시오 rs.close (); } catch (예외 e) {e.printstacktrace (); } rs = null; } if (st! = null) {try {// sql 명령을 실행하는 명령문 객체를 닫습니다 st.Close (); } catch (예외 e) {e.printstacktrace (); }} if (conn! = null) {try {// 연결 데이터베이스 연결 객체를 닫습니다. conn.close (); } catch (예외 e) {e.printstacktrace (); }}}} 3. JDBC를 사용하여 MySQL에서 큰 텍스트를 처리하십시오
MySQL의 텍스트 유형의 경우 다음 방법을 호출하여 설정할 수 있습니다.
preparedstatement.setcharacterstream (색인, 판독기, 길이); // 길이를 설정하고 int 유형으로 설정해야합니다.
MySQL의 텍스트 유형의 경우 다음 방법을 호출하여 얻을 수 있습니다.
reader = resultSet.getCharacterStream (String ColumnLabel); 2 String s = resultSt.getString (String ColumnLabel);
3.1. 테스트 예
1. SQL 테스트 스크립트를 작성하십시오
데이터베이스 생성 jdbcstudy; jdbcstudy 사용; 테이블 테스트 클럽 생성 (ID int 기본 키 AUTO_INCREMENT, 이력서 텍스트);
2. 다음과 같이 테스트 코드를 작성하십시오.
Me.gacl.demo; import java.io.file; import java.io.filereader; import java.io.filewriter; import java.io.reader; import java.sql.connection; import java.sql.preparedstatement; import java.sql.resultset; import; me.gacl.utils.jdbcutils; import org.junit.test;/*** @classname : jdbcoperaclob* @description : jdbc를 사용하여 mysql의 큰 텍스트를 작동 시키십시오* @author : Lonely canglang* @date : 2014-9-19 10:10:04 PM **/public classe jdbcoperaclob. @Method : add * @description : 데이터베이스에 큰 텍스트 데이터를 삽입 * @anthor : 发年 * */ @test public void add () {Connection conn = null; 준비된 상태 st = null; resultSet rs = null; 독자 독자 = null; try {conn = jdbcutils.getConnection (); 문자열 sql = "testClob (이력서) 값 (?)에 삽입"; st = conn.preparestatement (SQL); // 이러한 방식으로 얻은 경로는 "String Path = JDBCOPERACLOB.class.getClassOlder (). getResource ("data.txt ")를 사용하여"%20 "으로 대체 될 공간을"%20 "으로 대체합니다. getPath (); //"%20 "공간 경로 = Path.replaceall ("%20 ";" filereader (파일); JDBCUTILS.RELEASE (Conn, ST, RS)}* @Method : @Antor : 六后* / @test public void read () {null = null; testClob에서 id = 2 "; st = conn.preparestatement (sql); rs = st.ExecuteQuery (); String contenttr ="; String content = ""; if (rs.next ()) {// resultSet.getString ( "필드 이름")을 사용하여 큰 텍스트 내용의 내용을 얻으려면 = rs.getString ( "RESUMES"); // resultSet.getCharacterStream ( "필드 이름")을 사용하여 큰 텍스트 데이터의 내용을 가져 오려면 reader = rs.getCharacterStream ( "Resume"); 숯 버퍼 [] = 새로운 char [1024]; int len = 0; filewriter out = new filewriter ( "d : //1.txt"); while ((len = reader.read (buffer))> 0) {contenttr += new String (버퍼); out.write (Buffer, 0, Len); } out.close (); reader.close (); } system.out.println (컨텐츠); System.out.println ( "------------------------------------------------------------------------------------ System.out.println (contentstr); } catch (예외 e) {e.printstacktrace (); } 마침내 {jdbcutils.release (Conn, st, rs); }}}4. JDBC를 사용하여 MySQL 바이너리 데이터를 처리하십시오
MySQL의 Blob 유형의 경우 다음 방법 설정을 호출 할 수 있습니다.
준비된 상태. setbinarystream (i, 입력 스트림, 길이);
MySQL의 Blob 유형의 경우 다음 방법을 호출하여 다음 방법을 얻을 수 있습니다.
inputStream in = resultSet.getBinaryStream (String ColumnLabel); inputStream in = resultSet.getBlob (String ColumnLabel) .getBinaryStream ();
4.1. 테스트 예
1. SQL 테스트 스크립트를 작성하십시오
테이블 테스트 블로브 생성 (ID int 기본 키 AUTO_INCREMENT, image longBlob);
2. 다음과 같이 테스트 코드를 작성하십시오.
Me.gacl.demo; import java.io.file; import java.io.fileInputStream; import java.io.fileoutputStream; import java.io.inputstream; import java.sql.connection; import java.sql.preparedstatement; import java.sql.resultset; me.gacl.utils.jdbcutils; import org.junit.test;/ *** @classname : jdbcoperaclob* @description : jdbc를 사용하여 MySQL의 이진 데이터 (예 : 이미지, 사운드, 이진 텍스트)* @author : luke canglang* @date : 2014-919 10.19 10.19 10.19 10.19 10.19 10.19 10.19 10.19 10.19 10.19 10.19 jdbcoperablob { / *** @method : add* @description : 데이터베이스에 이진 데이터를 삽입* @anthor : luke canglang** / @test public void add () {connection conn = null; 준비된 상태 st = null; resultSet rs = null; try {conn = jdbcutils.getConnection (); 문자열 sql = "testBlob에 삽입 (이미지) 값 (?)"; st = conn.preparestatement (SQL); // 이러한 방식으로 얻은 경로는 문자열 경로 대신 "%20"으로 대체됩니다. jdbcoperablob.class.getClassLoader (). getResource ( "01.jpg"). getPath (); // "%20"교체는 공백으로 교체됩니다. Path.Replaceall ( "%20", ""); 파일 = 새 파일 (Path); fileInputStream fis = new FileInputStream (file); // 생성 된 스트림 st.setbinarystream (1, fis, (int) file.length ()); int num = st.ExecuteUpdate (); if (num> 0) {System.out.println ( "성공적으로 삽입!!"); } fis.close (); } catch (예외 e) {e.printstacktrace (); } 마침내 {jdbcutils.release (Conn, st, rs); }} / *** @method : 읽기* @description : 데이터베이스에서 이진 데이터를 읽습니다* @anthor : 六后** / @test public void read () {Connection conn = null; 준비된 상태 st = null; resultSet rs = null; try {conn = jdbcutils.getConnection (); 문자열 sql = "testBlob에서 id =?"에서 이미지를 선택하십시오. "; st = conn.preparestatement (SQL); St.SetInt (1, 1); rs = st.ExecuteQuery (); if (rs.next ()) {// inputStream in = rs.getBlob ( "image"). getBinaryStream (); //이 메소드는 = rs.getBinaryStream ( "image"); int len = 0; 바이트 버퍼 [] = 새로운 바이트 [1024]; fileoutputStream out = 새 FileOutputStream ( "d : //1.jpg"); while ((len = in.read (buffer))> 0) {out.write (buffer, 0, len); } in.close (); out.close (); }} catch (예외 e) {e.printstacktrace (); } 마침내 {jdbcutils.release (Conn, st, rs); }}}위는이 기사의 모든 내용입니다. 모든 사람의 학습에 도움이되기를 바랍니다. 모든 사람이 wulin.com을 더 지원하기를 바랍니다.