JDBC
JDBCUtils类中来实现:
public class JDBCUtils { private static String driver = null; private static String url = null; private static String username = null; private static String password = null; //加载驱动 static{ try { //db.properties是一个配置文件,里面有连接数据库所需要的信息 InputStream in = JDBCUtils.class.getClassLoader().getResourceAsStream("db.properties"); Properties prop = new Properties(); prop.load(in);//加载配置文件 driver = prop.getProperty("driver"); url = prop.getProperty("url"); username = prop.getProperty("username"); password = prop.getProperty("password"); Class.forName(driver);//加载驱动 } catch (Exception e) { throw new ExceptionInInitializerError(e); } } public static Connection getConnection() throws SQLException{ return DriverManager.getConnection(url, username, password);//获得connection } public static void release(Connection conn, Statement st, ResultSet rs){ //释放资源 if(rs != null){ try{ rs.close(); }catch(Exception e) { e.printStackTrace(); } rs = null; } if(st != null){ try{ st.close(); }catch(Exception e) { e.printStackTrace(); } st = null; } if(conn != null){ try{ conn.close(); }catch(Exception e) { e.printStackTrace(); } conn = null; } } }
JDBC处理大文本
在MySQL中,大文本是text类型,使用java操作数据库中的大文本需要两个方法setCharacterStream和getCharacterStream,一个是写入数据库的字符流,一个是从数据库中读取的字符流。setCharacterStream(index,Reader,length)有三个参数,Reader表示获取文件的流,length表示文件的长度,index表示参数的索引
建立数据库
create database test; use test; create table testclob ( id int primary key auto_increment, resume text );
public class Demo1 { @Test//向数据库中插入一个文本 public void add() throws FileNotFoundException { Connection conn = null; PreparedStatement st = null; ResultSet rs = null; try { conn = JDBCUtils.getConnection(); //使用上一节中的JDBCUtils String sql = "insert into testclob(resume) values(?)"; st = conn.prepareStatement(sql); //预处理sql语句 String path = Demo1.class.getClassLoader().getResource("1.txt").getPath();//在工程src目录下存放一个1.txt文件 File file = new File(path); st.setCharacterStream(1, new FileReader(file), file.length()); int num = st.executeUpdate(); //执行向数据库中插入 if(num > 0) { System.out.println("插入成功"); } } catch (SQLException e) { e.printStackTrace(); } finally { JdbcUtils.release(conn, st, rs); } } @Test //从数据库中读取文本 public void read() throws IOException { Connection conn = null; PreparedStatement st = null; ResultSet rs = null; try { conn = JDBCUtils.getConnection(); String sql = "select resume from testclob where id=?"; st = conn.prepareStatement(sql); st.setInt(1, 1); rs = st.executeQuery(); //执行sql语句 if(rs.next()){ Reader reader = rs.getCharacterStream("resume"); //获取字段未resume的项,也就是我们刚刚存到数据库的1.txt文件 char buffer[] = new char[1024]; int len = 0; FileWriter out = new FileWriter("D:\\1.txt"); //写到D盘下 while((len = reader.read(buffer)) > 0){ out.write(buffer, 0, len); } out.close(); reader.close(); } } catch (SQLException e) { e.printStackTrace(); } finally { JdbcUtils.release(conn, st, rs); } } }
参考:
https://blog.csdn.net/eson_15/article/details/51317001
立志如山 静心求实
浙公网安备 33010602011771号