import java.sql.Connection;
import java.sql.DriverManager;
public class DBHelper {
private static final String driver = "com.mysql.jdbc.Driver";//數(shù)據(jù)庫(kù)驅(qū)動(dòng)
private static final String url = "jdbc:mysql://localhost:3306/gumysql?useUnicon=true&characterEncoding=UTF-8";
private static final String username = "root";
private static final String password = "root";
static
{
try
{
Class.forName(driver);
}
catch (Exception e)
{
e.printStackTrace();
}
}
private static Connection conn = null;
//單例模式返回?cái)?shù)據(jù)庫(kù)連接
public static Connection getConnection() throws Exception
{
if(conn == null)
{
conn = DriverManager.getConnection(url, username, password);
return conn;
}
else
{
return conn;
}
}
}
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;
public class ReadDBPage {
/**
* @param pageNo 表示第幾頁(yè)
* @param pageSize 表示每頁(yè)的數(shù)量
* @return
*/
public List<String> query(int pageNo, int pageSize) {
//計(jì)算起始值,比如假如每頁(yè)條數(shù)為5,第一頁(yè)是0 - 4,第二頁(yè)是5 - 9;。。。。
int pageStart = (pageNo - 1) * pageSize;
Connection conn = null;
PreparedStatement stmt = null;
ResultSet rs = null;
String sql = " select * from compare limit ?,?; ";
List<String> mapList = new ArrayList<String>();
try {
conn = DBHelper.getConnection();
stmt = conn.prepareStatement(sql);
//把參數(shù)設(shè)置到 ?號(hào)里面
stmt.setInt(1, pageStart);
stmt.setInt(2, pageSize);
rs = stmt.executeQuery();
while (rs.next()) {
mapList.add(rs.getString("id"));
}
return mapList;
} catch (Exception e) {
e.printStackTrace();
return null;
} finally {
if (rs != null) {
try {
rs.close();
rs = null;
} catch (Exception e) {
e.printStackTrace();
}
}
if (stmt != null) {
try {
stmt.close();
stmt = null;
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
}
import java.util.List;
public class Bootstrap {
public static void main(String args[]){
ReadDBPage read = new ReadDBPage();
//查詢第1頁(yè)的數(shù)據(jù),每頁(yè)數(shù)據(jù)為5條
List<String> strList = read.query(1,5);
//查詢第2頁(yè)的數(shù)據(jù),每頁(yè)數(shù)據(jù)為5條
List<String> strList2 = read.query(2,5);
//查詢第2頁(yè)的數(shù)據(jù),每頁(yè)數(shù)據(jù)為4條
List<String> strList3 = read.query(2,4);
System.out.println(strList);
System.out.println(strList2);
System.out.println(strList3);
}
}