对数据库的操作无非就是增删改查,其中数查询操作最为复杂,所以将查询单独讲解,我这里用的Mysql数据库
增删改查操作
分页查询操作
1.查询结果以list返回
2.查询结果以jsonArray返回
3.查询总记录条数
先看一下相关的配置信息
public static final String USER_NAME = "root";
public static final String PWD = "123456789";
public static final String DRIVER = "com.mysql.jdbc.Driver";
public static final String URL = "jdbc:mysql://localhost:3306/web_demon";
/** 分页查询默认每页记录条数 */
public static final int PAGE_SIZE_DEFAULT = 10;
增删改操作
获取数据库连接对象
/**
* 获取数据库连接
* @return 数据库连接对象
*/
public Connection getConnection(Connection conn) {
if(conn == null){
try {
Class.forName(Config.DRIVER);
conn = DriverManager.getConnection(Config.URL, Config.USER_NAME, Config.PWD);
} catch (Exception e) {
e.printStackTrace();
}
}
return conn;
}
封装增删改操作
/**
* 新增,删除,插入操作
* @param sql 执行的sql语句
* 例如:新增语句 "insert into user (name,sex) values (?,?)";
* 删除语句 "delete from user where id=?";
* 修改语句 "update user set name=?,sex=? where id=? and sex=?";
* @param values 对应的参数值
* @return 影响条数,-1为异常
*/
private int execute(String sql,Object... values){
Connection conn = null;
PreparedStatement pStmt = null;
try {
conn = this.getConnection(conn);
pStmt = conn.prepareStatement(sql);
//设置参数
if(pStmt != null && values != null && values.length > 0){
for (int i = 0; i < values.length; i++) {
pStmt.setObject(i+1, values[i]);
}
}
int i =pStmt.executeUpdate();
return i;
} catch (Exception e) {
e.printStackTrace();
} finally {
if (conn != null) {
this.closeConnection(conn);
}
}
return -1;
}
调用方法
//新增
public static void insert(){
String sql = "insert into user (name,sex) values (?,?)";
Object[] values = new Object[]{"李四",0};
int