最近研究了下分页,做个总结。
1)数据库操作类,做简单封装 DB.java
package Test;
import java.sql.*;
public class DB {
// 加载驱动
static {
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e) {
System.out.println("驱动加载出错");
}
}
// 获取数据库连接
public static Connection getConn() {
Connection conn = null;
try {
conn = DriverManager.getConnection("jdbc:mysql://localhost/userinfo?user=root&password=abcd");
} catch (SQLException e) {
e.printStackTrace();
}
return conn;
}
// 关闭数据库连接
public static void closeConn(Connection conn) {
try {
if(conn != null) {
conn.close();
conn = null;
}
} catch (SQLException e) {
e.printStackTrace();
}
}
// 关闭Statement
public static void closeStmt(Statement stmt) {
try {
if(stmt != null) {
stmt.close();
stmt = null;
}
} catch (SQLException e) {
e.printStackTrace();
}
}
// 关闭ResultSet
public static void closeRs(ResultSet rs) {
try {
if(rs != null) {
rs.close();
rs = null;
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
*******************************************************
2)初始化数据类 initData.java
package Test;
import java.sql.*;
public class initData {
private static Connection conn = null;
private static PreparedStatement pstmt = null;
private static Statement stmt = null;
private static String sql = "insert into userinfo(id,username,age) values(?,?,?)";
// 总条数
private static int allCount = 10000;
// 分批条数
private static int preCount = 1000;
// 计数器
private static int count = 0;
public static void main(String[] args) {
CleanData();// 清除数据
InsertData();// 插入数据
}
/**
* DDL语句 建表语句
* create table userinfo ( id int(20) not null, username
* varchar(255), age varchar(255), primary key (id) )
*/
/**
* 插入数据 用addBatch()方法
* 当数据量达到1000时 提交一次
*/
private static void InsertData() {
try {
conn = DB.getConn();
pstmt = conn.prepareStatement(sql);
conn.setAutoCommit(false);
long start = System.currentTimeMillis();
for (int i = 1; i <= allCount; i++) {
pstmt.setInt(1, i);
pstmt.setString(2, "java" + i);
pstmt.setString(3, "20");
pstmt.addBatch();
if ((i % preCount) == 0) {
pstmt.executeBatch();
System.out.println("当前进行完毕===>" + (++count) * preCount
+ "条");
}
}
long end = System.currentTimeMillis();
System.out.println("数据插入成功!所用时间为: " + (end - start) + " ms");
} catch (Exception e) {
e.printStackTrace();
try {
conn.rollback();
} catch (SQLException e1) {
e1.printStackTrace();
}
System.out.println("数据出错,已进行回滚");
} finally {
try {
conn.