JDBC中级篇(MYSQL)——处理大文本(CLOB)

微笑注意:其中的JdbcUtil是我自定义的连接工具类:代码例子链接:

package b_blob_clob;

import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Reader;
import java.sql.Clob;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import util.JdbcUtil;

/**
 * 
 * JDBC处理大容量数据:
 * 		
 * 		字符:			
 * 						oracle:char、varchar2
 * 			存储字符内容:mysql:char、varchar长度有限。65335
 * 			大容量的字符字段:
 * 				mysql:text、longtext(4G的文本)
 * 				oracle:clob、longclob
 * 			JDBC中操作大文本的方法等命名也是参照oracle中的clob进行命名的
 * 
 * 		字节:
 * 			mysql:blob(65KB)  mediumbolb(16MB)  longblob(4GB)
 * 			oracle:同上
 * 
 * 注意:mysql默认设置最大上传数据包为1MB大小,所以要到安装目录下:
 * 		找到my.ini配置文件:添加一个变量max_allowed_packet=50M即可!
 * 
 * 
 * @author mzy
 *
 */
public class Demo01 {
	/**
	 * 关于CLOB:大文本
	 */
	
	public static void main(String[] args) {
		// write();
		
		read();
	}

	private static void read() {
		Connection conn = null;
		PreparedStatement stmt = null;
		ResultSet rs = null;
		
		
		try {
			conn = JdbcUtil.getConnection();
			String sql = "select * from news where id=?";
			stmt = conn.prepareStatement(sql);
			stmt.setInt(1, 1);
			rs = stmt.executeQuery();
			// 1. 直接用getString读;
			while(rs.next()) {
				String content = rs.getString("content");
				System.out.println(content);
			}
			
			stmt.setInt(1, 2);
			
			rs = stmt.executeQuery();
			while(rs.next()) {
				Clob clob = rs.getClob("content");
				Reader reader = clob.getCharacterStream();
				
				// 2. 用流的方式输出到文件中
				FileWriter writer = new FileWriter("e:/test.txt");
				char[] buf = new char[512];
				int len = 0;
				while((len=reader.read(buf)) != -1) {
					writer.write(buf, 0, len);
				}
				
				reader.close();
				writer.close();
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}

	private static void write() {
		Connection conn = null;
		PreparedStatement stmt = null;		
		try {
			conn = JdbcUtil.getConnection();
			String sql = "insert into news(title, content) values(?, ?)";
			stmt = conn.prepareStatement(sql);
			// 直接用setString
			stmt.setString(1, "标题一");
			stmt.setString(2, "假装是很长很长的文本!");
			// 执行
			stmt.executeUpdate();
			
			// 传入一个reader流对象;
			Reader reader = new FileReader("./src/LongText.txt");
			stmt.setString(1, "标题二");
			// 设置text字段:直接传入流对象
			stmt.setClob(2, reader);
			// 执行
			stmt.executeUpdate();
			
			System.out.println("添加成功!");
		} catch (SQLException e) {
			e.printStackTrace();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} finally {
			JdbcUtil.close(stmt, conn);
		}
	}
}


posted @ 2018-05-10 16:44  五彩世界  阅读(1352)  评论(0编辑  收藏  举报