处理文本
存储大文本
create table mytext(
id int primary key auto_increment,
content longtext
)
存储
File file = new File("JdbcUtils1.java");
FileReader fr = new FileReader(file);
pst.setCharacterStream(1, fr, (int) (file.length()));
获取:
Reader r = rs.getCharacterStream("content");
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.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
public class MyTextTest {
public static void main(String[] args) throws Exception {
// setText();
getText();
}
// 存储文件
public static void setText() throws SQLException, FileNotFoundException {
Connection con = JdbcUtils2.getConnection();
String sql = "insert into mytext values(null,?)";
PreparedStatement pst = con.prepareStatement(sql);
File f = new File("JdbcUtils1.java");
FileReader fr = new FileReader(f);
pst.setCharacterStream(1, fr, (int) f.length());
// 执行
int row = pst.executeUpdate();
if (row != 0) {
System.out.println("插入成功");
}
// 释放资源
JdbcUtils2.closePreparedStatement(pst);
JdbcUtils2.closeConnection(con);
}
// 获取文件
public static void getText() throws SQLException, IOException {
Connection con = JdbcUtils2.getConnection();
String sql = "select * from mytext where id =?";
;
PreparedStatement pst = con.prepareStatement(sql);
pst.setInt(1, 1);
ResultSet rs = pst.executeQuery();
if (rs.next()) {
Reader reader = rs.getCharacterStream("content");
FileWriter fw = new FileWriter("a.java");
char[] chs = new char[1024 * 100];
int len = 0;
while ((len = reader.read(chs)) != -1) {
fw.write(chs, 0, len);
fw.flush();
}
reader.close();
fw.close();
}
JdbcUtils2.closeResultSet(rs);
JdbcUtils2.closePreparedStatement(pst);
JdbcUtils2.closeConnection(con);
}
}