JDBC 强封装
苦于学习了反射,却不知道在哪里使用?我这里给大伙整一个反射的小型实战
是使用反射封装JDBC的操作
因为查询需要支持复杂查询,所以没有办法去封装
剩下的CUD操作,都使用反射进行了强封装
如果你能看懂,并自己写下对用的代码,那么,你的反射就入门了!
封装
类装载与初始化
"com.mysql.cj.jdbc.Driver"
是在 Mysql8 以后,使用的
数据库连接和用户名、密码,需要按照个人需求修改
static {
try {
Class.forName("com.mysql.cj.jdbc.Driver");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
private static final String url="jdbc:mysql://localhost:3306/SQLStudy?serverTimezone=UTC";
private static final String name="admin";
private static final String password="123";
//受影响的行数
private int count=0;
private Connection conn = null;
private PreparedStatement stmt = null;
private ResultSet resultSet = null;
获取连接和状态
这些都是死代码,没什么好说的
/**
* 获取数据库连接
* @return
*/
protected Connection getConnection() {
try {
conn = DriverManager.getConnection(url, name, password);
} catch (SQLException throwables) {
throwables.printStackTrace();
}
return conn;
}
/**
* 获取preparedStatement
* @param sql
* @param list
* @return
*/
protected PreparedStatement getStatement(String sql, List list) {
getConnection();
try {
stmt = conn.prepareStatement(sql);
} catch (SQLException throwables) {
throwables.printStackTrace();
}
if (list!=null && list.size()>0) {
for (int i = 0; i < list.size(); i++) {
try {
stmt.setObject(i+1,list.get(i));
} catch (SQLException throwables) {
throwables.