数据库数据很多,每次读5000条左右,用分页的方式循环读完,下面是测试代码,现在需要分页的代码,可以写在我发的测试代码上面,尽量详细,谢谢。
package webtest;
import java.sql.*;
import java.io.BufferedWriter;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.File;
public class test5{
static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
static final String DB_URL = "jdbc:mysql://localhost:3306/gumysql";
static final String USER = "root";
static final String PASS = "123456";
public static final String FILE_NAME = "again1.txt";//要创建的文件名
public static final String fn = "F:/NEWtest/";//文件指定存放的路径
public static void creatFile(String fn, String fileName) {
File folder = new File(fn);
//文件夹路径不存在
if (!folder.exists() && !folder.isDirectory()) {
System.out.println("文件夹路径不存在,创建路径:" + fn);
folder.mkdirs();
} else {
System.out.println("文件夹路径存在:" + fn);
}
// 如果文件不存在就创建
File file = new File(fn + fileName);
if (!file.exists()) {
System.out.println("文件不存在,创建文件:" + fn+ fileName);
try {
file.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
} else {
System.out.println("文件已存在,文件为:" + fn+ fileName);
}
}
public static void wf(String file, String conent) {
BufferedWriter out = null;
try {
out = new BufferedWriter(new OutputStreamWriter(
new FileOutputStream(file, true)));
out.write(conent+"\r\n");
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) {
Connection conn = null;
Statement stmt = null;
try{
creatFile(fn, FILE_NAME);
Class.forName("com.mysql.jdbc.Driver");
System.out.println("连接数据库...");
conn = DriverManager.getConnection(DB_URL,USER,PASS);
System.out.println(" 实例化Statement对象...");
stmt = conn.createStatement();
String sql;
sql = "SELECT id, name, url ,country FROM websites ";
ResultSet rs = stmt.executeQuery(sql);
String fn = "F://NEWtest//again1.txt";
wf(fn,"ID ,站点名称, 站点,country.");
while(rs.next()){
int id = rs.getInt("id");
String name = rs.getString("name");
String url = rs.getString("url");
String country = rs.getString("country");
System.out.print("ID: " + id);
System.out.print(", 站点名称: " + name);
System.out.print(", 站点 URL: " + url);
System.out.print(", country: " + country);
System.out.print("\n");
wf(fn,id+"," + name+ "," + url+ "," + country);
}
rs.close();
stmt.close();
conn.close();
}catch(SQLException se){
se.printStackTrace();
}catch(Exception e){
e.printStackTrace();
}finally{
try{
if(stmt!=null) stmt.close();
}catch(SQLException se2){
}
try{
if(conn!=null) conn.close();
}catch(SQLException se){
se.printStackTrace();
}
}
System.out.println("Goodbye!");
}
}