JDBC学习之路-对大文本数据的操作

1,建立一个大文本数据的库

create table clob(
big_lettle text
)charset utf8;

2,用JDBC对该库进行操作

为了演示,找了当前目录下的一个java文件
代码里的JDBCUtils所有的方法都是静态
用来注册驱动,连接数据库.(具体代码看-入门篇-)

public class ClobText {

    public static void main(String[] args) throws SQLException, IOException{
    creat();
    read();
    }
    //将文本输入到数据库中
    static public void creat() throws SQLException, IOException{
    Connection con = null;
    PreparedStatement ps = null;
    ResultSet rs = null;
    try {
        //建立连接
        con = JDBCUtils.getConnection();
        //创建语句
        String sql = "insert into clob(big_lettle) values(?)";
        ps = con.prepareStatement(sql);
        //读取文件
        File file = new File("src/JDBC/JDBCUtils.java");
        //读取文件
        Reader read = new BufferedReader(new FileReader(file));
        //1  为当前行中指定的列
        ps.setCharacterStream(1,read,(int)file.length());
        read.close();
        //执行语句
        int i = ps.executeUpdate();
        System.out.println("i:"+i);
    }finally{
       JDBCUtils.free(rs, ps, con);

    }


    }
    //将数据库的内容读取到文本中
    static void read() throws SQLException, IOException{
    Connection con = null;
    PreparedStatement ps = null;
    ResultSet rs = null;
    try {
        //建立连接
        con = JDBCUtils.getConnection();
        //创建语句
        String sql = "select big_lettle from clob";
        ps = con.prepareStatement(sql);
        rs = ps.executeQuery();
        while(rs.next()){
        //将数据库内容存储到src目录下JDBCUtils_2.java文件
        File file = new File("src/JDBCUtils_2.java");
        // 1  为当前行中指定的列
        Clob clob = rs.getClob(1);
        //读出流获取clob的内容
        Reader read = clob.getCharacterStream();
        /*
         * 也可以直接写成:
         * read = rs.getCharacterStream(1);
         * 1  为当前行中指定的列
         */

        //写入流
        Writer writer = new BufferedWriter(new FileWriter(file));

        char[] buff = new char[1024];    
        //将clob内容写入buff字符串中然后将buff写入文件中
        for(int i =0;(i=read.read(buff))>0;){
            writer.write(buff,0,i);
        }
        writer.close();
        read.close();
        }

    }finally{
        JDBCUtils.free(rs, ps, con);
    }


    }

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值