當使用jdbc從mysql中查詢大量數據時,有可能會導致內存溢出。為了避免這種情況的發生可以對數據庫進行分頁查詢。
public static void main(String[] args){
String url = "jdbc:mysql://localhost:3306/test";
String username = "username";
String password = "password";
int data_num = 0;
try {
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection(url, username,
password);
String sql = "SELECT ID,NAME FROM table_name limit ?,?";
PreparedStatement pst = con.prepareStatement(sql);
int pageSize = 10000;
int pageId = 0;
do {
pst.setInt(1, pageId * pageSize);
pst.setInt(2, pageSize);
ResultSet rs = pst.executeQuery();
boolean isEmpty = true;
while (rs.next()) {
isEmpty = false;
id = rs.getLong(1);
name = rs.getString(2);
data_num++;
}
if (isEmpty) {
break;
}
pageId++;
} while (true);
con.close();
} catch (SQLException se) {
se.printStackTrace();
}
利用上述的代碼可以對數據庫表進行遍歷處理。