JDBC_CLOB文本大对象操作

在这里插入图片描述

package com.lzy.jdbc;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileReader;
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 Demo07 {
	
	
	public static void main(String[] args) {
		Connection conn=null;
		PreparedStatement ps=null;
		ResultSet rs = null;
		Reader r=null;
		
		try {
			Class.forName("com.mysql.jdbc.Driver");
			conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/testjdbc","root","123456");
//			ps=conn.prepareStatement("insert into t_user(username,myInfo)values(?,?)");
//			ps.setString(1, "lzy");
//			ps.setClob(2, new FileReader(new File("d:/a.txt"))); //将文本文件内容直接输入到数据库中
			//将程序中的字符串输入到数据库的CLOB字段中
			//ps.setClob(2, new BufferedReader(new InputStreamReader(new ByteArrayInputStream("aaaaaa".getBytes()))));
			
			ps=conn.prepareStatement("select * from t_user where id=?");
			ps.setObject(1,1040);
			rs=ps.executeQuery();
			while(rs.next()) {
				Clob c=rs.getClob("myInfo");
				r=c.getCharacterStream();
				int temp=0;
				while((temp=r.read())!=-1) {
					System.out.print((char)temp);
				}
			}
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally{
			try {
				if(ps!=null){
					ps.close();
				}
			} catch (SQLException e) {
				e.printStackTrace();
			}
			try {
				if(conn!=null){
					conn.close();
				}
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
	}
}

代码中

		ps=conn.prepareStatement("insert into t_user(username,myInfo)values(?,?)");
			ps.setString(1, "lzy");
			ps.setClob(2, new FileReader(new File("d:/a.txt"))); //将文本文件内容直接输入到数据库中
	

是直接把文件中的文本保存到数据库中

ps.setClob(2, new BufferedReader(new InputStreamReader(new ByteArrayInputStream("aaaaaa".getBytes()))));

是直接把程序中的字符串输入到数据库中

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值