@param start 起始页数 pageN 每页条数
一、没有数据库连接池
public List<Map<String, String>> findfy(int start, int pageN) {
List<Map<String, String>> result = new ArrayList<>();
Map<String, String> m = new HashMap<>();
String sql = "select * from books limit ?,?";
try {
Connection connection = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/bookgl?useSSL=false&useUnicode=true&characterEncoding=utf-8&serverTimezone=GMT%2B8",
"root", "123456");
PreparedStatement preparedStatement = connection.prepareStatement(sql);
preparedStatement.setInt(1, start);
preparedStatement.setInt(2, pageN);
ResultSet resultSet = preparedStatement.executeQuery();
resultSet.next();
m.put("name", resultSet.getString("b_name"));
result.add(m);
} catch (SQLException throwables) {
throwables.printStackTrace();
}
return result;
}
二·、没有数据连接池用QueryRunner类
public List<Map<String, Object>> findfy1(int start, int pageN) {
List<Map<String,Object>> result=new ArrayList<>();
String sql="select * from books limit ?,?";
try {
Connection c= DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/bookgl?useSSL=false&useUnicode=true&characterEncoding=utf-8&serverTimezone=GMT%2B8",
"root", "123456");
result = super.query(c,sql,new MapListHandler(),start,pageN);
} catch (SQLException throwables) {
throwables.printStackTrace();
}
return result;
}
三、有数据库连接池不用queryRunner类
public List<Map<String, String>> findfy2(int start, int pageN) {
List<Map<String,String>> result=new ArrayList<>();
Map<String,String> m=new HashMap<>();
ComboPooledDataSource pooledDataSource=new ComboPooledDataSource();
String sql="select * from books limit ?,?";
pooledDataSource.setJdbcUrl("jdbc:mysql://127.0.0.1:3306/bookgl?useSSL=false&useUnicode=true&characterEncoding=utf-8&serverTimezone=GMT%2B8");
try {
pooledDataSource.setDriverClass("com.mysql.jdbc.driver");
Connection c= pooledDataSource.getConnection("root","123456");
PreparedStatement p=c.prepareStatement(sql);
p.setInt(1,0);
p.setInt(2,1);
ResultSet r= p.executeQuery();
r.next();
m.put("name",r.getString("b_name"));
result.add(m);
} catch (SQLException | PropertyVetoException throwables) {
throwables.printStackTrace();
}
return result;
}
四、有数据库连接池用queryRunner类
public List<Map<String, Object>> findfy3(int start, int pageN) {
List<Map<String,Object>> result=new ArrayList<>();
ComboPooledDataSource pooledDataSource=new ComboPooledDataSource();
String sql="select * from books limit ?,?";
pooledDataSource.setJdbcUrl("jdbc:mysql://127.0.0.1:3306/bookgl?useSSL=false&useUnicode=true&characterEncoding=utf-8&serverTimezone=GMT%2B8");
try {
pooledDataSource.setDriverClass("com.mysql.jdbc.driver");
Connection c= pooledDataSource.getConnection("root","123456");
result= super.query(sql,new MapListHandler(),start,pageN);
} catch (SQLException | PropertyVetoException throwables) {
throwables.printStackTrace();
}
return result;
}
五。总结
java.sql包是java提供的最原始的JDBC类库,里面常用DriverManger Connection Statement …
数据库连接池就不用介绍了吧 我用的从c3p0记得放包
QueryRunner是org.apache.commons.dbutils下面的对结果集进行操作的类。非常好用哈