首页 > 代码库 > JDBC学习笔记(三)大文本数据的读写

JDBC学习笔记(三)大文本数据的读写

一、用JDBC向数据库插入大文本数据

String sql = "insert into my_clob values (null, ?)";
ps = conn.prepareStatement(sql);
File f = new File("D:\\BaiduNetdiskDownload\\mysql\\jdbc.sql");
Reader reader = new BufferedReader(new FileReader(f));
ps.setCharacterStream(1, reader , f.length());
int res = ps.executeUpdate();
System.out.println(res);
reader.close();


二、从数据库读取大文本数据写入到文件中

方式一:直接把数据保存到字符串中

String big_text = rs.getString("bit_text");
File f = new File("D:\\BaiduNetdiskDownload\\mysql\\jdbc.bak.sql");
Writer wt = new FileWriter(f);
wt.write(big_text);
wt.close();

方式二:通过ResultSet对象rs获取输入流读取数据,创建输出流写到文件

Reader rd = rs.getCharacterStream("bit_text");
File f = new File("D:\\BaiduNetdiskDownload\\mysql\\jdbc.bak.sql");
Writer wt = new FileWriter(f);
char[] buff = new char[1024];
int i = 0;
while ((i = rd.read(buff)) != -1)
{
  wt.write(buff,
0, i);
}
wt.close();
rd.close();

方式三、通过Clob对象获取输入流

cb = rs.getClob("bit_text");
Reader rd = cb.getCharacterStream();
File f = new File("D:\\BaiduNetdiskDownload\\mysql\\jdbc.bak.sql");
Writer wt
= new FileWriter(f);
char[] buff = new char[1024];
int i = 0;
while ((i = rd.read(buff)) != -1)
{
  wt.write(buff,
0, i);
}
wt.close();
rd.close();

 

JDBC学习笔记(三)大文本数据的读写