勿忘初心——JDBC基础回顾

使用JDBC操作数据库的基本步骤

  1. 加载驱动
Class.forName("com.mysql.cj.jdbc.Driver");
  1. 建立连接
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/vip_test?serverTimezone=UTC&characterEncoding=utf8&useCursorFetch=true", "root", "123");
  1. 创建Statement对象,查询数据
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("select * from user");
  1. 关闭资源
if(conn != null) conn.close();
if(stmt != null) stmt.close();
if(rs != null) rs.close();

实际业务场景下存在的问题及解决方法

  1. 一次查询千万级数据时容易产生内存溢出,可以使用游标分批读取数据

游标:提供一种客户端部分读取服务端结果集的机制

在JDBC中也提供了对游标的支持,使用PreparedStatment

PreparedStatement pstmt = conn.prepareStatement(sql);
pstmt.setFetchSize(1);  // 设置每次读取一条数据
ResultSet rs = pstmt.executeQuery();
  1. 数据库某个字段存储大量数据(如存储的博客内容很大),一次读取也容易产生内存溢出,可以使用流方式,将内容分段读取
InputStream in = rs.getBinaryStream("blog"); // 获取对象流
File f = new File("fileURL");
OutputStream out = new FileOutputStream(f);
int temp = 0;
// 边读边写
while((temp = in.read()) != -1) {
    out.write(temp);
}
  1. 插入海量数据到数据库,如果一条一条插入,将非常耗时,可以使用批量插入
stmt = conn.createStatement();
for (String userName : users) {
    stmt.addBatch("insert into vip_user(user_name) values('" + userName + "')");
}
stmt.executeBatch();
stmt.clearBatch();

猜你喜欢

转载自blog.csdn.net/chenshufeng115/article/details/108295592