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);
}
}
}