基于JDBC对数据库员工表进行增删改查

创建员工实体类employee

添加get、set、toString方法

public class Employee {
    private int empid;
    private String empname;
    private String emppwd;
    private double salary;
    private Date birthdy;

    public int getEmpid() {
        return empid;
    }

    public void setEmpid(int empid) {
        this.empid = empid;
    }

    public String getEmpname() {
        return empname;
    }

    public void setEmpname(String empname) {
        this.empname = empname;
    }

    public String getEmppwd() {
        return emppwd;
    }

    public void setEmppwd(String emppwd) {
        this.emppwd = emppwd;
    }

    public Double getSalary() {
        return salary;
    }

    public void setSalary(Double salary) {
        this.salary = salary;
    }

    public Date getBirthdy() {
        return birthdy;
    }

    public void setBirthdy(Date birthdy) {
        this.birthdy = birthdy;
    }

    @Override
    public String toString() {
        return "Employee{" +
                "empid=" + empid +
                ", empname='" + empname + '\'' +
                ", salary=" + salary +
                '}';
    }
}

创建CRUD(增删改查)实体类

1、通过静态代码块读取配置文件加载驱动
2、properties配置文件参考配置文件
3、获取连接方法getConnection()
4、关闭资源方法closeResource()
5、测试新增员工信息方法
使用Statement对象获取sql命令,缺点:sql语句必须使用字符串的拼接,使用起来比较麻烦。
6、测试员工登录
使用Statement执行sql命令测试登录时,由于SQL语句是通过拼接完成的,那么就有可能存在SQL注入,缺陷:当我们输入为’ or 1=1 #时,会避过用户名和密码的检测
7、增加、删除、修改、查询方法都类似,修改sql语句即可

  • 测试员工登录方法时,使用@Test运行不出来,所以使用了main方法,知道原因的q一下。
public class CRUD {
    static String driver;
    static String url;
    static String user;
    static String password;
    //通过读取配置文件加载驱动
    static {
        InputStream is = CRUD.class.getClassLoader().getResourceAsStream("dbconfig.properties");
        //InputStream is = new FileInputStream("src/dbconfig.properties");
        Properties prop = new Properties();
        try {
            prop.load(is);
            driver = prop.getProperty("driver");
            url = prop.getProperty("url");
            user = prop.getProperty("user");
            password = prop.getProperty("password");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private Statement stmt;

    //获取连接对象
    public static Connection getConnection(){
        try {
            Class.forName(driver);
            return DriverManager.getConnection(url,user,password);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    //关闭资源
    public static void closeResource(Connection conn, Statement stmt, ResultSet resl){
        if (resl != null){
            try {
                resl.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }

        if (stmt != null){
            try {
                stmt.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }

        if (conn != null){
            try {
                conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }

    //测试新增员工信息
    @Test
    public void testAdd(){
        //获取连接
        Connection conn = CRUD.getConnection();
        //获取sql命令对象
        Statement stmt = null;
        try {
            stmt = conn.createStatement();
            //创建员工类对象
            Employee emp = new Employee();
            emp.setEmpname("lisi");
            emp.setEmppwd("1234");
            emp.setSalary(8000d);
            emp.setBirthdy(new Date(23512354L));
            //新增员工的sql,使用sattement只能拼接sql
            String sql = "INSERT INTO employee (`empname`,`emppwd`,`salary`,`birthday`) VALUES" +
                    "('" + emp.getEmpname() + "','" + emp.getEmppwd() + "'," + emp.getSalary() + ",NOW())";
            //执行sql,stmt.executeUpdate(sql)返回成功执行得sql语句的条数
            if (stmt.executeUpdate(sql)>0){
                System.out.println("成功添加一个员工!");
            }else {
                System.out.println("新增失败!");
            }

        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            CRUD.closeResource(conn,stmt,null);
        }
    }

    //测试登录
    public static void main(String[] args) throws Exception{
        Scanner sc = new Scanner(System.in);
        System.out.print("请输入用户名:");
        String userName = sc.nextLine();
        System.out.print("请输入密码:");
        String userPwd = sc.nextLine();
        Connection conn = CRUD.getConnection();
        Statement stmt = conn.createStatement();
        String sql = "SELECT empid,empname,salary from employee WHERE empname='"+userName+"' AND emppwd='"+userPwd+"'";
        //执行查询
        ResultSet rs = stmt.executeQuery(sql);
        //从结果集里取数据
        Employee emp = null;
        if (rs.next()){
            emp = new Employee();
            emp.setEmpid(rs.getInt(1));
            emp.setEmpname(rs.getString(2));
            emp.setSalary(rs.getDouble(3));
        }
        if (emp != null){
            System.out.println("登录成功!");
            System.out.println(emp);
        }else {
            System.out.println("登陆失败!");
        }
        CRUD.closeResource(conn,stmt,rs);
    }
}

对于statement对象的缺陷,我们可以使用它的子类PreparedStatement,sql语句中我们就可以使用?表示需要的值,在使用PreparedStatement对象给?赋值

//获取连接
        Connection conn = DBUtils.getConnection();
        //创建sql脚本
        String sql = "insert into employee (empname,emppwd,salary,birthday)" + "values (?,?,?,?)";
        //创建PreparedStatement
        PreparedStatement pstmt = conn.prepareStatement(sql);
        //给sql语句的?号占位符赋值,下标从1开始
        pstmt.setString(1,"Tom");
        pstmt.setString(2,"1234");
        pstmt.setDouble(3,5000);
        pstmt.setDate(4,new Date(1234123L));
        //执行SQL命令
        int count  = pstmt.executeUpdate();//返回影响的行数
  • 1
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,下面是一个简单的员工信息系统的示例,包括了基本的增删改查操作: 1. 首先,我们需要建立一个名为 `Employee` 的实体类,用于员工信息: ```java public class Employee { private int id; private String name; private int age; private String gender; public Employee(int id, String name, int age, String gender) { this.id = id; this.name = name; this.age = age; this.gender = gender; } public int getId() { return id; } public String getName() { return name; } public int getAge() { return age; } public String getGender() { return gender; } } ``` 2. 接下来,我们需要建立一个名为 `EmployeeDao` 的 DAO 类,用于实现对员工信息的增删改查操作。在该类中,我们需要建立连接数据库的方法以及对应的增删改查方法: ```java public class EmployeeDao { private Connection conn; public EmployeeDao() { try { Class.forName("com.mysql.jdbc.Driver"); conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/employees", "root", "password"); } catch (ClassNotFoundException | SQLException e) { e.printStackTrace(); } } public void add(Employee employee) { try { PreparedStatement ps = conn.prepareStatement("INSERT INTO employee VALUES (?, ?, ?, ?)"); ps.setInt(1, employee.getId()); ps.setString(2, employee.getName()); ps.setInt(3, employee.getAge()); ps.setString(4, employee.getGender()); ps.executeUpdate(); } catch (SQLException e) { e.printStackTrace(); } } public void delete(int id) { try { PreparedStatement ps = conn.prepareStatement("DELETE FROM employee WHERE id = ?"); ps.setInt(1, id); ps.executeUpdate(); } catch (SQLException e) { e.printStackTrace(); } } public void update(Employee employee) { try { PreparedStatement ps = conn.prepareStatement("UPDATE employee SET name = ?, age = ?, gender = ? WHERE id = ?"); ps.setString(1, employee.getName()); ps.setInt(2, employee.getAge()); ps.setString(3, employee.getGender()); ps.setInt(4, employee.getId()); ps.executeUpdate(); } catch (SQLException e) { e.printStackTrace(); } } public Employee getById(int id) { try { PreparedStatement ps = conn.prepareStatement("SELECT * FROM employee WHERE id = ?"); ps.setInt(1, id); ResultSet rs = ps.executeQuery(); if (rs.next()) { return new Employee(rs.getInt("id"), rs.getString("name"), rs.getInt("age"), rs.getString("gender")); } } catch (SQLException e) { e.printStackTrace(); } return null; } public List<Employee> getAll() { List<Employee> employees = new ArrayList<>(); try { Statement stmt = conn.createStatement(); ResultSet rs = stmt.executeQuery("SELECT * FROM employee"); while (rs.next()) { employees.add(new Employee(rs.getInt("id"), rs.getString("name"), rs.getInt("age"), rs.getString("gender"))); } } catch (SQLException e) { e.printStackTrace(); } return employees; } } ``` 3. 最后,我们可以在 `main` 方法中调用 `EmployeeDao` 的方法来执行相应的操作: ```java public static void main(String[] args) { EmployeeDao dao = new EmployeeDao(); // 添加员工信息 dao.add(new Employee(1, "张三", 20, "男")); // 获取指定 ID 的员工信息 Employee employee = dao.getById(1); System.out.println(employee.getName() + " " + employee.getAge() + " " + employee.getGender()); // 修改员工信息 dao.update(new Employee(1, "李四", 22, "女")); // 删除员工信息 dao.delete(1); // 获取所有的员工信息 List<Employee> employees = dao.getAll(); for (Employee e : employees) { System.out.println(e.getName() + " " + e.getAge() + " " + e.getGender()); } } ``` 以上就是一个简单的基于 JDBC员工信息系统的示例,您可以根据自己的需求进行相应的修改和优化。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值