分页显示
public class jdbcTest {
public static void main(String[] args) throws SQLException {
Connection con=getConnection("root", "root");// 获取数据库连接
paging(con, 1,2);//方法名调用数据库连接,且定义显示第几行到第几行
releaseConnection(con);// 释放数据库连接
}
/**
* 分页查询
* @param con
* @param startIndex
* @param total
*/
public static void paging(Connection con,int startIndex,int total){
try{
String sql="select * from student limit ?,?";
PreparedStatement pstmt=con.prepareStatement(sql);
pstmt.setInt(1, startIndex);
pstmt.setInt(2, total);
ResultSet rs=pstmt.executeQuery();
while(rs.next()){
System.out.println("学生ID:"+rs.getInt("stuId")+",学生姓名:"+rs.getString("stuName")+",学生性别:"+rs.getString("stuSex")+",学生年龄:"+rs.getInt("stuAge"));
}
rs.close();
pstmt.close();
}catch(Exception e){
e.printStackTrace();
}
}
/**
* 数据库连接
* @param dbUserName
* @param dbPassword
* @return
* @throws SQLException
*/
public static Connection getConnection(String dbUserName,String dbPassword) throws SQLException{
Connection con=null;//声明连接对象
String jdbcName="com.mysql.jdbc.Driver";//驱动程序类名
String dbUrl="jdbc:mysql://localhost:3306/book?"//数据库Url
+"useUnicode=true&characterEncoding=UTF8";//防止乱码
try {
Class.forName(jdbcName);
con=DriverManager.getConnection(dbUrl,dbUserName,dbPassword);//获取数据库连接
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return con;
}
/**
* 释放数据库连接
* @param con
*/
public static void releaseConnection(Connection con){
try{
if(con!=null){
con.close();
}
}catch(Exception e){
e.printStackTrace();
}
}
}