package com.imau.dao.base;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.util.List;
import com.iamu.jdbc.DBUtils;
import com.imau.util.Sqlutil;
//数据库操作的基本父类
public class DaoImpl implements Dao {
private Connection conn;
private PreparedStatement pstm;
private ResultSet rs;
private String sql;
//反射
Class<T> type;
//获取T的class对象,获取泛型的类型,泛型是在被子类继承时才确定
public DaoImpl()
{
//给反射泛型
//获取子类的类型
Class clazz=this.getClass();
//获取父类的类型
//getGenericSuperclass()用来获取当前类的父类的类型
//ParameterizedType表示的是带泛型的类型
ParameterizedType parameterizedType=(ParameterizedType) clazz.getGenericSuperclass();
//获取具体的泛型类型getActualTypeArguments获取具体的泛型的类型
//这个方法会返回一个type的数组
Type[] types=parameterizedType.getActualTypeArguments();
//获取具体的泛型的类型
this.type=(Class<T>) types[0];
}
@Override
public boolean add(T t) {
try{
sql=Sqlutil.getSql(t,1);
//1.获取连接
conn=DBUtils.getConn();
//2.执行命令
pstm=conn.prepareStatement(sql);
//3.填充占位符 如何调用对象的get方法
Sqlutil.initPstm(t,pstm,1);
//4.执行命令
pstm.executeUpdate();
//5.关闭连接
DBUtils.close(conn,pstm,null);
}catch(Exception e){
e.printStackTrace();
}
return false;
}
//按照主键
@Override
public int delete(T t) {
try{
sql=Sqlutil.getSql(t, 2);
conn=DBUtils.getConn();
pstm=conn.prepareStatement(sql);
Sqlutil.initPstm(t, pstm, 2);
//3.处理结果
pstm.executeUpdate();
//4.关闭连接
DBUtils.close(conn,pstm,null);
}catch(Exception e){
e.printStackTrace();
}
return 0;
}
@Override
public int update(T t) {
try{
sql=Sqlutil.getSql(t, 3);
//1.获取连接
conn=DBUtils.getConn();
pstm=conn.prepareStatement(sql);
//2.2填充占位符 如何调用对象的get方法
Sqlutil.initPstm(t, pstm, 3);
//3.处理结果
pstm.executeUpdate();
//4.关闭连接
DBUtils.close(conn,pstm,null);
}catch(Exception e){
e.printStackTrace();
}
return 0;
}
//用户对象:
@Override
public T find(T t) {
try{
//select*from tablename where and
sql=Sqlutil.getSql(t, 4);
System.out.println("sql="+sql);
//1.获取连接
conn=DBUtils.getConn();
pstm=conn.prepareStatement(sql);
//2.2填充占位符 如何调用对象的get方法
Sqlutil.initPstm(t, pstm, 4);
//3.处理结果
rs=pstm.executeQuery();
//数据库的元数据
ResultSetMetaData rsmd=rs.getMetaData();
//创建一个对象
T t2=type.newInstance();
Field fields[]=t.getClass().getDeclaredFields();
while(rs.next()){
//获取查询数据库的列数
for(int i=0; i<rsmd.getColumnCount();++i){
//字段列名->对象属性赋值
String colName =rsmd.getColumnName(i+1);
Object colVau=rs.getObject(colName);
fieldVau(t2,fields,colName,colVau);
}
}
//4.关闭连接
DBUtils.close(conn,pstm,rs);
}catch(Exception e){
e.printStackTrace();
}
return null;
}
public void fieldVau(T t,Field fields[],String colName,Object colVau){
for(Field field:fields){
try{
//找到对应的属性
if(field.getName().equals(colName)){
//属性描述
PropertyDescriptor pd=new PropertyDescriptor(field.getName(),t.getClass());
//属性可读的方法
Method method=pd.getReadMethod();
method.invoke(t, colVau);
}
}catch(Exception e){
e.printStackTrace();
}
}
System.out.println(t);
}
@Override
public List<T> query(T t) {
// TODO Auto-generated method stub
return null;
}
}
package com.imau.util;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import com.imau.entry.User;
import com.mysql.jdbc.PreparedStatement;
public class Sqlutil {
private static String tableName="";
private static String sql="";
private static StringBuffer sflied=new StringBuffer();
private static StringBuffer sValue=new StringBuffer();
private static StringBuffer sfield;
//填充预处理命令占位符
public static <T> PreparedStatement initPstm(T t,java.sql.PreparedStatement pstm,int sqlType){
Field fields[]=t.getClass().getDeclaredFields();
try{
for (int i=0;i<fields.length;i++){
//属性描述
PropertyDescriptor pd=new PropertyDescriptor(fields[i].getName(),t.getClass());
//属性可读的方法
Method method=pd.getReadMethod();
//添加 修改
if(sqlType==1 ){
//排除主键
if(i!=0){
pstm.setObject(i, method.invoke(t));
}
}else if( sqlType==3){
//排除主键
if(i==0){
//upate ewt nds where id=?
pstm.setObject(fields.length, method.invoke(t));
}else{
pstm.setObject(i, method.invoke(t));
}
}else if( sqlType==2)//删除
{
//字段是否是主键
if(fields[i].getName().equals("id")){
pstm.setObject(i, method.invoke(t));
}
}else if(sqlType==4){
int flag=0;
Object v=method.invoke(t);
if(v!=null ){
pstm.setObject(1,v);
}
}
}
} catch (Exception e){
e.printStackTrace();
}
return null ;
}
//返回sql语句1 2 3 4
public static <T> String getSql(T t,int sqlType){
tableName=t.getClass().getSimpleName().toLowerCase();
if(sqlType==1){
sql="insert into"+tableName+"(";
Field fields[]=t.getClass().getDeclaredFields();
for (int i=1;i<fields.length;i++){
if(i!=fields.length-1){
sflied.append(fields[i].getName()).append(",");
sValue.append("?");
}else{
sflied.append(fields[i].getName());
sValue.append("?");
}
}
sql=sql+sflied.toString()+") values("+sValue.toString()+")";
}
if(sqlType==2){
String sql="delete from "+tableName+" where id = ?";
}
if(sqlType==3){
sql="update"+tableName+" set ";
Field fields[]=t.getClass().getDeclaredFields();
for (int i=1;i<fields.length;i++){
if(i!=fields.length-1){
sflied.append(fields[i].getName()).append("=").append("?,");
}else{
sflied.append(fields[i].getName()).append("=").append("?");
}
}
sql=sql+sflied+" where id=?";
}
//new User(“ddd”,“123456”,“12355”)
if(sqlType==4){
try{
int flag=0;
sql="select *from"+tableName+"where uname=? and ss";
Field fields[]=t.getClass().getDeclaredFields();
for (int i=0;i<fields.length;i++){
//属性描述
PropertyDescriptor pd=new PropertyDescriptor(fields[i].getName(),t.getClass());
//属性可读的方法
Method method=pd.getReadMethod();
Object v=method.invoke(t);
if(v!=null ){
if(flag!=0){
sfield. append("and ");
sfield. append(fields[i].getName()).append(" = ? ");
}else{
sfield. append(fields[i].getName()).append(" = ? ");
flag=1;
}
}
}
sql=sql+sfield ;
}catch(Exception e){
e.printStackTrace();
}
}
return sql;
}
}
package com.imau.dao.student;
import com.imau.dao.base.DaoImpl;
import com.imau.entry.Student;
public class StudentDaoImpl extends DaoImpl implements StudentDao{
}
package com.imau.entry;
public class Student {
private Integer id;
private String name;
private String no;
private Integer age;
private String nation;
public Student(){
}
public Student( String name, String no, Integer age, String nation) {
this.name = name;
this.no = no;
this.age = age;
this.nation = nation;
}
public Student(Integer id, String name, String no, Integer age, String nation) {
this.id = id;
this.name = name;
this.no = no;
this.age = age;
this.nation = nation;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getNo() {
return no;
}
public void setNo(String no) {
this.no = no;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public String getNation() {
return nation;
}
public void setNation(String nation) {
this.nation = nation;
}
@Override
public String toString() {
return "Student [id=" + id + ", name=" + name + ", no=" + no + ", age=" + age + ", nation=" + nation + "]";
}
}
package com.imau.dao.base;
import java.util.List;
//数据库操作的基本规范
public interface Dao {
//增删改查
public boolean add(T t);
public int delete(T t);
public int update(T t);
public T find(T t);
public List<T> query(T t);
}
package com.iamu.jdbc;
import java.lang.reflect.Field;
import java.sql.*;
import java.util.ArrayList;
import javax.sql.*;
import com.imau.dao.user.UserDaoImpl;
import com.imau.entry.User;
public class Text {
public static void main(String[] args) throws Exception{
//Connection conn;
//Statement stm;
//ResultSet rs;
//PreparedStatement pstm;
//jdbc:mysql://
//String url="jdbc:mysql://localhost:3306/student";
//String user="root";
//String password="123456";
//1.准备驱动
//2.注册驱动:驱动接口 连接接口 执行命令接口 结果集接口
//Driver driver=new com.mysql.jdbc.Driver();
//注册驱动:驱动名
//Class.forName("com.mysql.jdbc.Driver");
//3.注册管理器
//conn=DriverManager.getConnection(url, user, password);
//获取执行sql命令
//stm=conn.createStatement();
//5.执行sql命令
//rs=stm.executeQuery("SELECT*from user ");
//预处理命令
//pstm=conn.prepareStatement("select *from user where uname =? and upass =?");
//填充占位符
//pstm.setString(1, "text");
//pstm.setString(2, "text");
//执行命令
// rs=pstm.executeQuery();
//6.处理结果
//while(rs.next()){
// int id=rs.getInt(1);
//String name=rs.getString(2);
//String pass=rs.getString(3);
//System.out.println(id+","+name+","+pass);
//}
//7.关闭
//rs.close();
//stm.close();
// conn.close();
//类的描述信息
//Class<User> clazz=User.class;
//Field fields[]=clazz.getDeclaredFields();
//for (int i=0;i<fields.length;i++){
// System.out.println(fields[i].getName());
//}
// System.out.println(clazz.getName());
UserDaoImpl daoImpl=new UserDaoImpl();
//daoImpl.add(new User("ddd","123456","13904719999"));
//daoImpl.delete(new User("admin123","123456","12355"));
//daoImpl.delete(new User("ddd","123456","12355"));
daoImpl.find(new User("ddd","123456","13904719999"));
}
}