Java最基础的增删查改

    xiaoxiao2025-05-29  11

    撰写时间:2019.05.25 增删查改是编程中最基础的代码,也是做一个系统中最不可少的代码,如何写出java最基础的增删查改呢,下面给大家分享。 首先我们以一个用户表为例:

    一、定义连接参数、SQL执行语句 private Connection con=null;//连接 private PreparedStatement ps=null;//准备好要执行SQL语句 private ResultSet rs=null;//结果集 private String findAll=“select *from user”; private String findById=“select *from user where userid=?”; private String update=“update user set username=?,password=?, sex=?,createtime=?,detime=? where userid=?”; private String insert=“insert into user(username,password, sex,createtime,detime) values(?,?,?,?,?)”; 二、编写几步走:a.获取驱动管理连接;b.执行sql语句,判断传值是否为空(无参数则省略此步骤),设置参数值,执行方法;c.获取结果集id,遍历条数;d.关闭链接,返回条数。 1.新增用户表 public int insert(User user) { int i = 0; try { con = DBUtilDemo.getConnection(); PreparedStatement ps = con.prepareStatement(insert, Statement.RETURN_GENERATED_KEYS); if(user.getPassword()!=null){ ps.setString(2, user.getPassword()); } if(user.getUsername()!=null){ ps.setString(1, user.getUsername()); } ps.executeUpdate(); rs = ps.getGeneratedKeys(); if (rs.next()) { i = Integer.parseInt(rs.getLong(1) + “”); } } catch (SQLException e) { e.printStackTrace(); } finally { DBUtilDemo.close(con, ps, rs); } return i; } 2.删除用户表 public int deleteById(int id) { int i=0; try { con=DBUtilDemo.getConnection(); ps=con.prepareStatement(deleteById); ps.setInt(1,id); i=ps.executeUpdate(); } catch (SQLException e) { e.printStackTrace(); }finally{ DBUtilDemo.close(con, ps, rs); } return i; } 3.查询用户表 public List findAll() { User user=null; Listusers=null; try { con=DBUtilDemo.getConnection(); ps=con.prepareStatement(findAll); rs=ps.executeQuery(); users=new ArrayList(); while (rs.next()) { user=new User(); user.setUserid(rs.getInt(“userid”)); user.setUsername(rs.getString(“username”)); user.setPassword(rs.getString(“password”)); users.add(user); } } catch (SQLException e) { e.printStackTrace(); }finally{ DBUtilDemo.close(con, ps, rs); } return users; } 4.修改用户表 public int update(User user) { int i=0; try { con=DBUtilDemo.getConnection(); ps=con.prepareStatement(update); if(user.getPassword()!=null){ ps.setString(2, user.getPassword()); } if(user.getUsername()!=null){ ps.setString(1, user.getUsername()); } ps.setInt(6, user.getUserid()); i=ps.executeUpdate(); } catch (SQLException e) { e.printStackTrace(); }finally{ DBUtilDemo.close(con, ps, rs); } return i; } 完。 猜你喜欢: java连接数据库 java开发常用代码规范 使用File类创建文件进行遍历 利用java反射机制获取类的所有属性和方法 Java异常处理机制 如何使用Collections解决多线程安全问题 如何封装java驱动连接SQL,与数据库交互

    最新回复(0)