JDBC 关于大文本数据
大文本数据Clob,在不同的数据库中类型名不一致,有的是text格式,有的是clob,还有其他一些格式
package test;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Reader;
import java.io.Writer;
import java.sql.Clob;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Date;
public class ClobTest {
public static void main(String[] args) throws SQLException, IOException, ClassNotFoundException {
read();
}
static void create() throws SQLException, IOException {
Connection conn = null;
PreparedStatement ps = null;
ResultSet rs = null;
Reader reader = null;
try {
conn = JdbcUtils.getConnection();
//3,Statement用于“运送”sql语句和sql语句执行结果
String sql = "insert into clob_test(big_text) values (?)";
ps = conn.prepareStatement(sql);
//ps.setAsciiStream(int parameterIndex, InputStream x, int length)
File file = new File("src/test/ClobTest.java");
reader = new BufferedReader(new FileReader(file));
ps.setCharacterStream(1, reader,file.length());
//4,执行sql
int count = ps.executeUpdate();
System.out.println(count);
} finally {
JdbcUtils.free(rs, ps, conn);
if(reader!=null) {
reader.close();//为了方便这样写了
}
}
}
private static void read() throws ClassNotFoundException, SQLException, IOException {
Connection conn = null;
Statement st = null;
ResultSet rs = null;
Date bithday = null;
try {
conn = JdbcUtils.getConnection();
st = conn.createStatement();
rs = st.executeQuery("select big_text from clob_test");
while(rs.next()) {
Clob clob = rs.getClob(1);
BufferedReader reader = new BufferedReader(clob.getCharacterStream());
//Reader rd = rs.getCharacterStream(1);//这样也可以的
//String s = rs.getString(1);//String也可以 关键是你的内存有没有那么大
File file = new File("src/ClobTest_bak.java");
BufferedWriter writer = new BufferedWriter(new FileWriter(file));
String line = null;
while((line=reader.readLine())!=null) {
writer.write(line);
writer.newLine();
writer.flush();
}
writer.close();
reader.close();
}
} finally {
JdbcUtils.free(rs, st, conn);
}
}
}