JDBC高级版本(JDBCVersion3)


JDBC高级版本(JDBCVersion3)
此版本是JDBC的高级版本,这里有很多知识是值得大家去考究的与学习的,比如:反射,泛型,多态等。对于一般水平的同志来讲理解起来不是那么的简单,不过理解了之后此JDBC还是挺好用的。这个版本的JDBC是可以在实际编码中使用的,和前两个版本有本质上的区别。本人能力有限,只希望能相互学习,共同进步,不足之处多多包涵!

一:JAVA工程
JDBC高级版本(JDBCVersion3)
文章图片


二:测试数据库
<1>数据库和表
JDBC高级版本(JDBCVersion3)
文章图片

<2>数据库初始值
JDBC高级版本(JDBCVersion3)
文章图片


三:实体类
package cn.gson.jdbcversion3.entity;
/**
* 学生实体类
* @author Administrator
*
*/
public class Student {
private int id;
private String stu_name;
private int stu_age;
private String stu_gender;

public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getStu_name() {
return stu_name;
}
public void setStu_name(String stu_name) {
this.stu_name = stu_name;
}
public int getStu_age() {
return stu_age;
}
public void setStu_age(int stu_age) {
this.stu_age = stu_age;
}
public String getStu_gender() {
return stu_gender;
}
public void setStu_gender(String stu_gender) {
this.stu_gender = stu_gender;
}
public Student(int id, String stu_name, int stu_age, String stu_gender) {
super();
this.id = id;
this.stu_name = stu_name;
this.stu_age = stu_age;
this.stu_gender = stu_gender;
}
public Student() {
super();
}
}

四:BaseDao类
package cn.gson.jdbcversion3;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
* baseDao类(主要用于创建和关闭连接)
* @author Administrator
*
*/
public class BaseDao {
private static final String DRIVER = "com.mysql.jdbc.Driver";
private static final String URL = "jdbc:mysql://localhost:3306/test";
private static final String USERNAME = "root";
private static final String PASSWORD = "1234";
private static Connection con;

/**
* 创建连接的方法
* @return
*/
public static Connection getConnection(){
try {
//加载驱动
Class.forName(DRIVER);
//创建连接
con = DriverManager.getConnection(URL, USERNAME, PASSWORD);
} catch (ClassNotFoundException | SQLException e) {
e.printStackTrace();
}
return con;
}

/**
* 关闭连接的方法 (关闭连接的顺序需要注意rs->pt->con)
*/
public static void closeConnection(ResultSet rs,PreparedStatement pt,Connection con){
if(rs != null){
try {
rs.close();
rs = null;
} catch (SQLException e) {
e.printStackTrace();
}
}
if(pt != null){
try {
pt.close();
pt = null;
} catch (SQLException e) {
e.printStackTrace();
}
}
if(con != null){
try {
con.close();
con = null;
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}

五:CRUTDdao类
package cn.gson.jdbcversion3;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

import cn.gson.jdbcversion3.entity.Student;

/**
* CRUTDao类
* @author Administrator
*
*/
public class CRUTDao {

public static void main(String[] args) {
//int flag =0;

//String sql = "delete from student where stu_name=?";
//flag = CRUTDao.allUpdate(sql,"小胡");

//String sql = "insert into student (stu_name,stu_age,stu_gender) values(?,?,?)";
//flag = CRUTDao.allUpdate(sql,"小明",18,"男");

//String sql = "update student set stu_name=? where stu_gender=?";
//flag = CRUTDao.allUpdate(sql,"小刘","男");
//System.out.println(flag);

CRUTDao cd = new CRUTDao<>(Student.class);
String sql = "select * from student";
List list = cd.allSelect(sql);
System.out.println("id"+"\t"+"姓名"+"\t"+"年龄"+"\t"+"性别");
for (Student student : list) {
System.out.println(student.getId()+"\t"+student.getStu_name()+
"\t"+student.getStu_age()+"\t"+student.getStu_gender());
}
}

private static Connection con;
private static Statement st;
private static PreparedStatement pt;
private static ResultSet rs;
private Class c;
public CRUTDao(Class c) {
this.c = c;
}
/**
* 执行所有的删,改,增
* @return
*/
//这里Object...objects相当于动态绑定参数,实际上objects会返回一个对象数组,这是多态的典型应用
public static int allUpdate(String sql,Object...objects){
int row = 0;
try {
//创建连接
con = BaseDao.getConnection();
if(con != null){
pt = con.prepareStatement(sql);
//动态绑定参数
bound(objects);
row = pt.executeUpdate();
}
} catch (SQLException e) {
e.printStackTrace();
}finally{
//关闭连接
BaseDao.closeConnection(rs, pt, con);
}
return row;
}

/**
* 执行所有的查询(返回结果是一个List)
*/
public List allSelect(String sql,Object...objects){
List list = new ArrayList();
con = BaseDao.getConnection();
try {
pt = con.prepareStatement(sql);
bound(objects);
rs = pt.executeQuery();
while(rs.next()){
//给list中放入数据库里查询出来的值
list.add(toBean());
}
【JDBC高级版本(JDBCVersion3)】} catch (SQLException e) {
e.printStackTrace();
}finally{
BaseDao.closeConnection(rs, pt, con);
}
return list;
}

/**
* 数据转换(类似于将数据库的值给一个实体类的对象)
* @return
*/
privateT toBean() {
T t =null;
try {
//初始化给定的泛型类
t= c.newInstance();
//从rs中得到从数据库表中查出来的值
ResultSetMetaData rm = rs.getMetaData();
//利用反射的到给定泛型类的所有方法
Method[] methods = c.getMethods();
//rm.getColumnCount()是数据库表的所有列,i需要从1开始,并且可以等于rm.getColumnCount()。
//不然会出现有的查询结果为null或没有值
for(int i=1; i<=rm.getColumnCount(); i++){
//得到数据库表的所有列名
String name = rm.getColumnName(i);
//遍历给定的泛型类的所有方法
for (Method method : methods) {
//因为实体类的方法有setXxx(),getXxx(),在这里需要用数据库表的列名拼凑一个set方法。即set+数据库列名首字母变为大写+剩余字母
//然后再做判断,如果满足条件则将其值给t对象,最后返回t加入到list中
if(method.getName().equals("set"+name.substring(0,1).toUpperCase()+name.substring(1))){
method.invoke(t, rs.getObject(name));
}
}
}
} catch (SQLException | InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
e.printStackTrace();
}
return t;
}

/**
* 参数绑定
* @param objects
*/
private static void bound(Object[] objects) {
for (int i = 0; i < objects.length; i++) {
try {
//因为参数是从1开始
pt.setObject(i+1, objects[i]);
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}



    推荐阅读