动态修改数据库数据

该文章介绍了如何使用Java的JDBC和三层架构思想来实现数据库操作。通过JDBCTemplate工具类动态获取实体类的属性并构建SQL更新语句,利用反射机制处理get和set方法,实现对任意实体类的数据修改功能。JDBCUtils工具类则负责数据库连接的获取和关闭。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

这里我运用的是jdbc连接数据库,运用三层架构的思想

首先我写了两个工具类 JDBCUtils和JDBCTemplate,用来连接数据库和动态获取sql语句和获取实体类的方法

JDBCTemplate

public class jdbcTemplate {
    public final static String TABLE_PREFIX="";
    private static String tableName="";
    private static Field[] fields;
    public static List getFields(Object obj){
        Class c=obj.getClass();

        String className=obj.getClass().getSimpleName();
//        TABLE_PREFIX+
        tableName=className.toLowerCase();

        fields=c.getDeclaredFields();
        Method[]method=c.getMethods();
        List list=new ArrayList();
        for (int i=0;i<fields.length;i++){
            String m="get"+fields[i].getName().toUpperCase().charAt(0)+fields[i].getName().substring(1);
            for (int j=0;j<method.length;j++){
                if (method[j].getName().endsWith(m)){
                    try {
                        list.add(method[j].invoke(obj,null));
                    }catch (Exception e){
                        e.printStackTrace();
                        return null;
                    }
                }
            }
        }return list;

    }
    public static   String getUpdateSQL(Object obj){
        List list=getFields(obj);
        StringBuffer sql=new StringBuffer();
        sql.append("UPDATE");
        sql.append("`"+tableName+"`");
        sql.append("SET");
        for (int i=1;i<fields.length;i++){
            if (!list.get(i).equals("")){
            sql.append("`"+fields[i].getName()+"`");
            sql.append("=?");
            if (!list.get(i+1).equals("")){
                    sql.append(",");
                }
        }
        }
        sql.append("WHERE");
        sql.append(" ");
        sql.append(fields[0].getName());
        sql.append("=?");
        System.out.println(sql.toString());
        return sql.toString();
    }
}

运用反射动态的获取实体类里面的get方法,运用stringbuffer凭借反射获取实体类属性名并且拼接成SQL语句

JDBCUtils

public class JDBCUtils {
   
   /**
    * 
    * @Description 获取数据库的连接
    * @author shkstart
    * @date 上午9:11:23
    * @return
    * @throws Exception
    */
   public static Connection getConnection() throws Exception {
      // 1.读取配置文件中的4个基本信息
      InputStream is = ClassLoader.getSystemClassLoader().getResourceAsStream("jdbc.properties");

      Properties pros = new Properties();
      pros.load(is);

      String user = pros.getProperty("user");
      String password = pros.getProperty("password");
      String url = pros.getProperty("url");
      String driverClass = pros.getProperty("driverClass");

      // 2.加载驱动
      Class.forName(driverClass);

      // 3.获取连接
      Connection conn = DriverManager.getConnection(url, user, password);
      return conn;
   }
   /**
    * 
    * @Description 关闭连接和Statement的操作
    * @author shkstart
    * @date 上午9:12:40
    * @param conn
    * @param ps
    */
   public static void closeResource(Connection conn,Statement ps){
      try {
         if(ps != null)
            ps.close();
      } catch (SQLException e) {
         e.printStackTrace();
      }
      try {
         if(conn != null)
            conn.close();
      } catch (SQLException e) {
         e.printStackTrace();
      }
   }
   /**
    * 
    * @Description 关闭资源操作
    * @author shkstart
    * @date 上午10:21:15
    * @param conn
    * @param ps
    * @param rs
    */
   public static void closeResource(Connection conn,Statement ps,ResultSet rs){
      try {
         if(ps != null)
            ps.close();
      } catch (SQLException e) {
         e.printStackTrace();
      }
      try {
         if(conn != null)
            conn.close();
      } catch (SQLException e) {
         e.printStackTrace();
      }
      try {
         if(rs != null)
            rs.close();
      } catch (SQLException e) {
         e.printStackTrace();
      }
   }
}

下面是Dao层代码

StudentDao接口

public interface StudentDao {
    Student findOneById(int id) throws Exception;

    Student login(String name,String password) throws Exception;

    void addOne(Student student) throws Exception;

     int update(Object obj) throws Exception;

    void delete(int id) throws Exception;
}

StudentDaoimpl

 @Override
    public int update(Object obj) throws Exception {
    Connection conn = JDBCUtils.getConnection();
        List list= com.util.jdbcTemplate.getFields(obj);
        String sql=jdbcTemplate.getUpdateSQL(obj);
        PreparedStatement ps=conn.prepareStatement(sql);
        int count=1;
        for (int i=1;i<list.size();i++){
                if (!list.get(i).equals("")) {
                    System.out.println(list.get(i));
                    ps.setObject(count++, list.get(i));
            }

        }
        ps.setInt(count,(Integer) list.get(0));
        int result=ps.executeUpdate();

        JDBCUtils.closeResource(conn,ps);
return result;
    }

这里运用反射获取实体类里面属性,判断是否为空为空不执行prepareStatement的传参

Service层 

StduentService接口

public interface StudentService {
    boolean lginStu(String name,String password)throws  Exception;
    void register(Student student)throws Exception;
   String  update()throws Exception;
}

StudentServiceimpl

  public   String update()throws Exception {
        Scanner sc=new Scanner(System.in);
        boolean flag=false;
      Student student=new Student();
        Class c=student.getClass();
        Field[]  fields=c.getDeclaredFields();
        Method[]method=c.getMethods();
        for (int i=0;i<fields.length;i++) {
            String m = "set" + fields[i].getName().toUpperCase().charAt(0) + fields[i].getName().substring(1);
            for (int j = 0; j < method.length; j++) {
//                System.out.println(method[j].getName());
                if (method[j].getName().endsWith(m)){
                        System.out.println(method[j].getName());
                    if (method[j].getName().equals("setId")){
                        System.out.println("请输入id");
                        String id=sc.nextLine();
                        int id1=Integer.parseInt(id);
                        method[j].invoke(student,id1);
                    }else {
                        String s = sc.nextLine();
                        method[j].invoke(student, s);
                    }
                }
            }
        }
int result=studentDao.update(student);
        if (result!=0){
            return "修改成功";
        }else {
            return "修改失败";
        }

//        studentDao.update();

    }

这里运用反射获取set方法对用户输入的数据进行传入对象

View层

    public void update() throws Exception {


        System.out.println( studentService.update());



        }

到此无论使用哪个实体类都可以动态修改数据库数据

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值