11package com .atguigu .dao .impl ;
22
3+
34import com .atguigu .utils .JdbcUtils ;
45import org .apache .commons .dbutils .QueryRunner ;
56import org .apache .commons .dbutils .handlers .BeanHandler ;
@@ -18,15 +19,25 @@ public abstract class BaseDao {
1819 /**
1920 * update()方法用来执行: Insert\Update\Delete
2021 * 如果返回-1表示执行失败
21- * @return
22+ * @return 返回影响行数
2223 */
2324 public int update (String sql ,Object ...args ){
25+ //1.创建连接
2426 Connection connection = JdbcUtils .getConnection ();
2527 try {
28+ //调用的是 QueryRunner 里的 update()方法, 这个方法 你传入连接,SQL语句和占位符的值,
29+ //它会自动创建preparedStatement对象,然后进行占位符赋值
30+ //然后执行SQL语句 并返回 影响行数
31+ //相当于是之前的
32+
33+ //2.创建preparedStatement对象
34+ //3.占位符赋值
35+ //4.发送SQL语句,并返回影响行数
2636 return queryRunner .update (connection ,sql ,args );
2737 } catch (SQLException e ) {
2838 e .printStackTrace ();
2939 }finally {
40+ //5.回收资源
3041 JdbcUtils .close (connection );
3142 }
3243 return -1 ;
@@ -42,13 +53,18 @@ public int update(String sql,Object...args){
4253 * @return
4354 */
4455 public <T > T queryForOne (Class <T >type , String sql ,Object ...args ){
56+ //1.创建连接
4557 Connection connection = JdbcUtils .getConnection ();
4658
4759 try {
60+ //2.创建preparedStatement对象
61+ //3.占位符赋值
62+ //4.发送SQL语句 并返回 结果集
4863 return queryRunner .query (connection ,sql ,new BeanHandler <T >(type ),args );
4964 } catch (Exception e ) {
5065 e .printStackTrace ();
5166 }finally {
67+ //5.回收连接
5268 JdbcUtils .close (connection );
5369 }
5470 return null ;
@@ -62,12 +78,16 @@ public<T> T queryForOne(Class<T>type, String sql,Object...args){
6278 * @param sql 执行的sql语句
6379 * @param args sql对应的参数值
6480 * @param <T> 返回类型的泛型
65- * @return
81+ * @return List<T> 返回List集合 结果集
6682 */
6783 public <T > List <T > queryForList (Class <T >type , String sql ,Object ...args ){
84+ //1.建立连接
6885 Connection connection = JdbcUtils .getConnection ();
6986
7087 try {
88+ //2.创建preparedStatement对象
89+ //3.占位符赋值
90+ //4.执行SQL语句 , 返回结果集
7191 return queryRunner .query (connection ,sql ,new BeanListHandler <T >(type ),args );
7292 } catch (Exception e ) {
7393 e .printStackTrace ();
@@ -84,8 +104,12 @@ public<T> List<T> queryForList(Class<T>type, String sql,Object...args){
84104 * @return
85105 */
86106 public Object queryForSingleValue (String sql ,Object ...args ){
107+ //1.创建连接
87108 Connection connection = JdbcUtils .getConnection ();
88109 try {
110+ //2.创建preparedStatement对象
111+ //3.占位符赋值
112+ //4.执行SQL语句,返回结果集
89113 return queryRunner .query (connection ,sql ,new ScalarHandler (),args );
90114 } catch (Exception e ) {
91115 e .printStackTrace ();
0 commit comments