mysql Java JDBC连接完整性约束冲突

zbdgwd5y  于 2023-06-21  发布在  Mysql
关注(0)|答案(1)|浏览(134)

我创建了一个switch case并创建了不同的类来创建Employee。当我创建一个员工时,在表中添加了一个条目,但我得到了这个错误:

Exception in thread "main" java.lang.RuntimeException: java.sql.SQLIntegrityConstraintViolationException: Duplicate entry '4' for key 'employee.PRIMARY'
    at com.siddhi.empapp.EmployeeDaoImpl.createEmployee(EmployeeDaoImpl.java:26)
    at com.siddhi.empapp.Main.main(Main.java:36)
Caused by: java.sql.SQLIntegrityConstraintViolationException: Duplicate entry '4' for key 'employee.PRIMARY'
    at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:118)
    at com.mysql.cj.jdbc.exceptions.SQLExceptionsMapping.translateException(SQLExceptionsMapping.java:122)
    at com.mysql.cj.jdbc.ClientPreparedStatement.executeInternal(ClientPreparedStatement.java:916)
    at com.mysql.cj.jdbc.ClientPreparedStatement.executeUpdateInternal(ClientPreparedStatement.java:1061)
    at com.mysql.cj.jdbc.ClientPreparedStatement.executeUpdateInternal(ClientPreparedStatement.java:1009)
    at com.mysql.cj.jdbc.ClientPreparedStatement.executeLargeUpdate(ClientPreparedStatement.java:1320)
    at com.mysql.cj.jdbc.ClientPreparedStatement.executeUpdate(ClientPreparedStatement.java:994)
    at com.siddhi.empapp.EmployeeDaoImpl.createEmployee(EmployeeDaoImpl.java:22)
    ... 1 more

这是主要的类开关情况:

case 1:
                    Employee emp=new Employee();
                    System.out.print("Enter ID: ");
                     id=sc.nextInt();
                    System.out.print("Enter Name: ");
                     name=sc.next();
                    System.out.print("Enter Salary: ");
                    double salary=sc.nextDouble();
                    System.out.print("Enter Age: ");
                    int age=sc.nextInt();
                    emp.setId(id);
                    emp.setName(name);
                    emp.setSalary(salary);
                    emp.setAge(age);
                    dao.createEmployee(emp);
                    break;

这就是实现:

@Override
    public void createEmployee(Employee emp) {
        con=DBConnection.createDBConnetion();
        String query="insert into employee values(?,?,?,?)";
        try {
            PreparedStatement pstm=con.prepareStatement(query);
            pstm.setInt(1,emp.getId());
            pstm.setString(2,emp.getName());
            pstm.setDouble(3,emp.getSalary());
            pstm.setInt(4,emp.getAge());
            pstm.executeUpdate();

            int cnt = pstm . executeUpdate();
            if(cnt!=0)
                System.out.println("Employee Inserted Successfully");
        }catch (SQLException e){
            throw new RuntimeException(e);
        }

    }
7hiiyaii

7hiiyaii1#

尝试查询数据库,检查数据库中是否有值4已经在数据库表中设置为主键的列中。如果是,则需要使用注解中建议的其他值。我建议修改表,使用AUTO_INCREMENT作为ID列。

相关问题