9.文本大对象操作之CLOB

package jdbc;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
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.SQLException;



public class Demo_main {
/*
 * CLOB(Character Large Object)用于存储大量的文本数据,一般以流的方式进行处理
 * 在建表的时候我们可以有多种数据类型,
 * 例如:tinytext的最大长度是255即[(2^8)-1]字符
 * 		text的最大长度65,535即[(2^16)-1]字符
 * 		mediumtext的最大长度为16,777,215[(2^24)-1]字符
 * 		longtext的最大长度是4,294,967,295即4GB也就是[(2^32)-1]字符
 */
	public static void main(String[] args){
		PreparedStatement ps1 = null;
		PreparedStatement ps2 = null;
		Connection c = null;
		ResultSet rs = null;
			try {
//加载驱动类
				Class.forName("com.mysql.jdbc.Driver");
//建立连接
				c = DriverManager.getConnection("jdbc:mysql://localhost:3306/jdbc的使用","root","root");				
//执行SQL语句					
				
				
				ps1 = c.prepareStatement("insert into infomyself (info) values (?)");
		//通过文件存储
				//ps1.setClob(1, new FileReader(new File("E:/临时/AAA.txt")));
		//通过字符串存储
				ps1.setClob(1, new BufferedReader(new InputStreamReader(new ByteArrayInputStream("my name is Pning.".getBytes()))));
				ps1.executeUpdate();
		//读取其内容
				ps2 = c.prepareStatement("select * from infomyself where id=?");
				ps2.setObject(1, 1);
				rs = ps2.executeQuery();
				while(rs.next()) {
					Clob cl = rs.getClob("info");
					Reader r = cl.getCharacterStream();
					int i = 0;
						while((i=r.read())!=-1){
							System.out.print((char)i);
						}
					System.out.println();
					r.close();
				}
				
			} catch (ClassNotFoundException e) {
				e.printStackTrace();
			} catch (SQLException e) {
				e.printStackTrace();
			} catch (IOException e) {						
				e.printStackTrace();
			}finally {
//关闭
				try {
					if(ps1 != null) {
						ps1.close();
						}
				} catch (SQLException e) {
					e.printStackTrace();
				}
				try {
					if(ps2 != null) {
						ps2.close();
						}
				} catch (SQLException e) {
					e.printStackTrace();
				}
				try {
					if(c != null) {
						c.close();						
					}
				} catch (SQLException e) {
					e.printStackTrace();
				}
			}
			
	}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值