`
qingtianzhu
  • 浏览: 14905 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

JDBC读写MySQL的BLOB和CLOB类型数据(带代码)

    博客分类:
  • JDBC
阅读更多
JDBC对LOB的读写
  在JDBC中提供了java.sql.Blob和java.sql.Clob两个类分别代表BLOB和CLOB数据
  •BLOB(Binary Large Object):用于存储大量的二进制数据
  •CLOB(Character Large Object):用于存储大量的文本数据

本文以MySQL为例,通过最基本的JDBC技术来处理大字段的插入、读取操作。

环境: MySQL5  JDK1.6

1)首先创建一张数据表:
  create table stuinfo(
      id int(11) not null auto_increment,
      name varchar(20)default null,
      content mediumtext , 
      image blob,
      primary key (id)
   );

2)先数据库中插入BLOB和CLOB类型的数据
package cn.wjz.jdbc;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;

import cn.wjz.db.ConnectionFactory;
import cn.wjz.db.DbClose;

public class LobWrite {

   public void LobW(){
       Connection conn = ConnectionFactory.getConnection() ;
       PreparedStatement pstmt = null ;
       String sql = 
           "insert into stuinfo(name,content,image) values(?,?,?)" ;
       try{
	   pstmt = conn.prepareStatement(sql) ;
	   pstmt.setString(1, "test") ;
	   /从文件中获取输入流———读取文本
	   File file = new File("D:\\wjz.gif"); 
            try{
                 InputStreamReader reader = new InputStreamReader
                                (new FileInputStream("D:\\test.txt"));
                 pstmt.setCharacterStream
                                    (2, reader, (int) file.length()); 
             }catch(Exception e){
                     e.printStackTrace() ;
             }
             File file1 = new File("D:\\wjz.gif"); 
             InputStream in;
             try {
	           in = new BufferedInputStream
                                        (new FileInputStream(file1));
                     pstmt.setBinaryStream
                                       (3, in, (int) file1.length()); 
             } catch (FileNotFoundException e) {
	            e.printStackTrace();
             } 
             if(pstmt.executeUpdate() == 1){
	          System.out.println("恭喜您成功添加记录!!");
             }else{
	          System.out.println("对不起您添加记录失败!!");
             }
         }catch(SQLException e){
	         e.printStackTrace();
		DbClose.close(pstmt , conn ) ;
         }
    }
	
    public static void main(String args[]){
	LobWrite lobtest = new LobWrite() ;
	lobtest.LobW() ;
    }
}

3)从MySql数据库中读取BLOB和CLOB类型数据:
package cn.wjz.jdbc;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.Reader;
import java.sql.Blob;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import cn.wjz.db.ConnectionFactory;
import cn.wjz.db.DbClose;

public class LobRead {
  public void lobread(){
     Connection conn = ConnectionFactory.getConnection();
     PreparedStatement pstmt = null;
     String sql = 
         "SELECT id,name,content,image FROM stuinfo WHERE name=?";
     ResultSet rs = null;
     BufferedReader br =null;
     try {
	  pstmt = conn.prepareStatement(sql);
	  pstmt.setString(1, "test");
	  rs = pstmt.executeQuery();
	  while (rs.next()) {
	  	Reader rd = rs.getCharacterStream(3);
	  	br = new BufferedReader(rd);
	  	String str = null;			
	  	while((str = br.readLine()) != null){
	  		System.out.println(str);
	  	}
	  	Blob blob = rs.getBlob(4);
	  	BufferedInputStream bis = 
                      new BufferedInputStream(blob.getBinaryStream());
	  	BufferedOutputStream bos = new BufferedOutputStream
                         (new FileOutputStream("d:/wjz.gif"));
	  	byte[] buffer = new byte[1024];
	  	int count = -1;
	  	while ((count = bis.read(buffer, 0, 1024)) != -1) {
	  		bos.write(buffer, 0, count);
	  	}
	  	bos.flush();
	  	bos.close();
	  	System.out.println("\n------->图片写好了!");
	  }
	} catch (SQLException e) {
	    e.printStackTrace();
	} catch (IOException e) {
	    e.printStackTrace();
	} finally {
	    DbClose.close(pstmt, conn);
	}
  }
  public static void main(String[] args) {
	LobRead lobread = new LobRead();
	lobread.lobread();
  }
}

在处理blob字段时候,由于直接处理的是二进制流,所以没啥问题。在处理clob字段的时候,由于数据库对clob是以字符的形式进行存储,这就有一个编码问题。本文虽然成功的插入读取了clob字段,但是还没有解决乱码问题,因为JDBC在获取到clob的时候,已经对其进行了编码,Reader reader = rs.getCharacterStream(1); 这就导致了编码的混乱,如果要彻底解决,还需要看看MySQL驱动的实现。通过非常规手段来解决。为了绕开此问题,可以将clob的数据存储为blog来操作,可以避免此问题。
1
2
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics