[java]代码库
package mysql4;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
public class TestPage {
private static Connection con = null;
private static PreparedStatement pre=null;
private static ResultSet result=null;
public static void main(String[] args) {
//1.加载数据库驱动
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e) {
System.out.println("加载失败!");
e.printStackTrace();
}
System.out.println("加载成功!");
//2.连接数据库
try {
con=DriverManager.getConnection("jdbc:mysql://localhost:3306/db_library", "root", "123");
} catch (SQLException e) {
System.out.println("连接数据库失败!");
e.printStackTrace();
}
System.out.println("成功连接数据库!");
/*MySQL分页语句
* select * from person limit M,N
* M表示从第M条数据开始,取N条记录
*/
try {
//page是第几页,pagecount是每页显示多少条记录
int page=3;
int pagecount=10;
pre=con.prepareStatement("select * from person limit ?,?");
pre.setInt(1, (page-1)*10);
pre.setInt(2, pagecount);
result=pre.executeQuery();
while(result.next()){
System.out.println(result.getInt("id"));
System.out.println(result.getString("name"));
System.out.println(result.getInt("age"));
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//4.释放数据库的资源
finally{
try {
if(result!=null)
result.close();
if(pre!=null)
pre.close();
if(con!=null)
con.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
System.out.println("执行成功!");
}
}