DAO
DAO的一些结构
BasicDAO
public class BasicDAO<T> { //泛型指定具体类型
private QueryRunner qr = new QueryRunner(); //属性
开发通用的dml方法
针对任意的表
//开发通用的dml方法,针对任意的表
public int update(String sql,Object... parameters) throws SQLException {
Connection connection = null;
try {
connection = JDBCUtilsByDruid.getConnection(); //得到连接
int update = qr.update(connection,sql,parameters); //得到修改的行数
return update;
} catch (SQLException e) {
throw new RuntimeException();
} finally {
JDBCUtilsByDruid.close(null,null,connection); //关闭连接
}
}
查询方法(返回多行多列)
public List<T> queryMulti(String sql,Class<T> clazz,Object... parameters) throws SQLException {
Connection connection = null;
List<T> query = null;
try {
connection = JDBCUtilsByDruid.getConnection();
query = qr.query(connection,sql,new BeanListHandler<T>(clazz),parameters);
} catch (SQLException e) {
throw new RuntimeException();
} finally {
JDBCUtilsByDruid.close(null,null,connection);
}
return query;
}
sql:sql语句,可以有?
clazz:传入一个类的Class对象,比如Person.class
parameters:给?赋值
查询(返回一行)
//查询单行结果的通用方法
public T querySingle(String sql,Class<T> clazz,Object... parameters) throws SQLException {
Connection connection = null;
try {
connection = JDBCUtils.getConnection();
return qr.query(connection,sql,new BeanHandler<T>(clazz),parameters);
//使用 BeanHandler方法
} catch (SQLException e) {
throw new RuntimeException();
} finally {
JDBCUtilsByDruid.close(null,null,connection);
}
}
查询(返回单行单列)
//查询单行单列的方法,即返回单值的方法
public Object queryScalar(String sql,Object... parameters) throws SQLException {
Connection connection = null;
try {
connection = JDBCUtilsByDruid.getConnection();
return qr.query(connection,sql,new ScalarHandler(),parameters);
//使用ScalarHandler方法
} catch (SQLException e) {
throw new RuntimeException();
} finally {
JDBCUtilsByDruid.close(null,null,connection);
}
}
PersonDAO
Person是映射表内容的类,PersonDAO需要继承BasicDAO,然后在里面写入自己的独特内容。
public class PersonDAO extends BasicDAO{
//继承BasicDAO,在这里面写独特的内容
private String name;
private int age;
}
TestDAO
测试PersonDAO对t01表的查找操作
public void testPersonDAO() throws SQLException {
PersonDAO personDAO = new PersonDAO();
List<Person> list = personDAO.queryMulti("select * from t01 where age=?",Person.class,18);
System.out.println("查询结果为");
for (Person person : list) {
System.out.println(person);
}
}
testWhileIdle is true, validationQuery not set解决方法 :
https://blog.csdn.net/weixin_42323802/article/details/82726267
dml操作
public void testPersonDAO() throws SQLException {
PersonDAO personDAO = new PersonDAO();
personDAO.update("insert into t01 values(?,?)","Hans",22);
}