服务器之家:专注于服务器技术及软件下载分享
分类导航

PHP教程|ASP.NET教程|JAVA教程|ASP教程|编程技术|正则表达式|C/C++|IOS|C#|Swift|Android|JavaScript|易语言|

服务器之家 - 编程语言 - JAVA教程 - BaseJDBC和CRUDDAO的写法实例代码

BaseJDBC和CRUDDAO的写法实例代码

2021-01-07 13:56周振宇 JAVA教程

这篇文章主要介绍了BaseJDBC和CRUDDAO的写法实例代码,代码注释十分详细,具有一定参考价值,需要的朋友可以了解下。

我们首先看下BASEJDBC的写法实例:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
package com.dao;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import com.mysql.jdbc.Driver;
public class BaseJDBC {
 // 表示你要操作的是哪种类型的数据库
 private final String DRIVER = "com.mysql.jdbc.Driver";
 // 表示你要连接的是哪一台电脑的服务器端口号是多少数据库的名字是什么
 private final String URL = "jdbc:mysql://localhost:3306/zzy";//有时这里需要加上字符集
 // 登录数据库的用户名
 private final String USERNMAE = "root";
 // 登录数据库的密码
 private final String PASSWORD = "root";
 /**
  * 注册驱动 获取连接
  *
  * @return
  */
 public Connection getConnection() {
  try {
   //Driver d=new Driver();
   // 注册驱动:反射(是一项很高深的技术)
   Class.forName(DRIVER);
   // 由连接大管家创建连接对象
   return DriverManager.getConnection(URL, USERNMAE, PASSWORD);
  } catch (ClassNotFoundException e) {
   //e.printStackTrace("数据库的驱动文件没有找到");
  } catch (SQLException e) {
   //数据库的连接错误
   e.printStackTrace();
  }
  return null;
 }
 /**
  * 关闭连接释放资源
  * @param con
  * @param st
  * @param rt
  */
 public void closeAll(Connection con, Statement st, ResultSet rt) {
  try {
   if (rt != null) {
    rt.close();
    rt = null;
   }
  } catch (SQLException e) {
   e.printStackTrace();
  }
  try {
   if (st != null) {
    st.close();
    st = null;
   }
  } catch (SQLException e) {
   e.printStackTrace();
  }
  try {
   if (con != null) {
    con.close();
    con = null;
   }
  } catch (SQLException e) {
   e.printStackTrace();
  }
 }
}

CRUDDAO 写法代码实例:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
package com.dao;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.sql.*;
import java.util.*;
import java.util.Map.Entry;
/**
 *
 * @author zzy
 *
 * 2016年12月1日下午1:49:49
 */
public class CRUDDAO<T> extends BaseJDBC {
 private Connection con = null;
 private PreparedStatement pt = null;
 private Statement st = null;
 private ResultSet rt = null;
 private Class<T> c;
 public CRUDDAO() {
 }
 public CRUDDAO(Class<T> c) {
  this.c = c;
 }
 /**
  * 查询操作要改造的地方 第一:参数必须抽象 第二:返回类型必须抽象
  *
  * @param <T>
  * @param <T>
  *
  * @return Map<Integer, List<T>>
  */
 public Map<Integer, List<T>> selectAll(Map<String, Object[]> m) {
  int index = 0;
  Map<Integer, List<T>> map = new LinkedHashMap<Integer, List<T>>();
  List<T> list = null;
  try {
   con = super.getConnection();
   if (con != null) {
    Set<Entry<String, Object[]>> set = m.entrySet();
    for (Entry<String, Object[]> entry : set) {
     list = new ArrayList<T>();
     pt = con.prepareStatement(entry.getKey());
     this.bind(entry.getValue());
     rt = pt.executeQuery();
     while (rt.next()) {
      list.add(this.toBean2());
     }
     map.put(++index, list);
    }
   } else {
    System.out.println("数据库连接失败");
   }
  } catch (SQLException e) {
   e.printStackTrace();
  } finally {
   super.closeAll(con, pt, rt);
  }
  return map;
 }
 /**
  * 将数据库查询到的数据进行封装 封装成实体类之后再返回给调用者
  *
  * @return
  */
 private T toBean() {
  T t = null;
  try {
   t = c.newInstance();
   Method[] m = c.getMethods();
   ResultSetMetaData rmt = rt.getMetaData();
   for (int i = 1, count = rmt.getColumnCount(); i <= count; i++) {
    String columName = rmt.getColumnName(i);
    columName = "set" + columName.substring(0, 1).toUpperCase()
      + columName.substring(1);
    for (int j = 0; j < m.length; j++) {
     if (columName.equals(m[j].getName())) {
      m[j].invoke(t, rt.getObject(i));
      break;
     }
    }
   }
  } catch (Exception e) {
   e.printStackTrace();
  }
  return t;
 }
 private T toBean2() {
  T t = null;
  try {
   // 创建反射类的实例
   t = c.newInstance();
   // 反射出所有字段
   Field[] field = c.getDeclaredFields();
   for (Field f : field) {
    // 根据反射的字段名得到数据库中的字段值
    Object value = rt.getObject(f.getName());
    f.setAccessible(true);// 打开私有字段的操作权限
    f.set(t, value);// 调用这个字段的公有的set方法封装字段的值
   }
  } catch (Exception e) {
   e.printStackTrace();
  }
  return t;
 }
 /**
  * 绑定参数
  *
  * @param obj
  */
 private void bind(Object[] obj) {
  try {
   if (obj != null) {
    for (int i = 0, k = obj.length; i < k; i++) {
     pt.setObject(i + 1, obj[i]);
    }
   }
  } catch (SQLException e) {
   e.printStackTrace();
  }
 }
 /**
  * 修改操作 进行的事务的控制 所有命令要么同时提交成功 要么同时回滚
  *
  * @param name
  * @param id
  * @return
  */
 public int[] updateAll(Map<String, Object[]> map) {
  int[] row = new int[map.size()];
  int index = 0;
  int error = 0;
  try {
   con = super.getConnection();
   if (con != null) {
    Set<Entry<String, Object[]>> set = map.entrySet();
    // 关闭连接对象的自动提交的功能
    con.setAutoCommit(false);
    for (Entry<String, Object[]> entry : set) {
     pt = con.prepareStatement(entry.getKey());
     this.bind(entry.getValue());
     row[index] = pt.executeUpdate();
     if (row[index] == 0) {
      throw new Exception("修改失败,数据回滚!");
     }
     index++;
    }
   } else {
    System.out.println("数据库连接失败");
   }
  } catch (Exception e) {
   error++;
   e.printStackTrace();
  } finally {
   if (error > 0) {
    try {
     // 将前面已经执行的命令回滚
     con.rollback();
    } catch (SQLException e) {
     e.printStackTrace();
    }
   } else {
    try {
     // 全部提交
     con.commit();
    } catch (SQLException e) {
     e.printStackTrace();
    }
   }
   super.closeAll(con, st, null);
  }
  return row;
 }
}

总结

以上就是本文关于BaseJDBC和CRUDDAO的写法实例代码的全部内容,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对服务器之家网站的支持!

原文链接:http://blog.csdn.net/fvdfsdafdsafs/article/details/53420589

延伸 · 阅读

精彩推荐