在代码或mysql数据库中的某处出错。获取java.sql.SQLIntegrityConstraintViolationException

时间:2019-04-03 14:11:21

标签: java mysql

我正在尝试更新mysql表,但出现错误

  

java.sql.SQLIntegrityConstraintViolationException:无法添加或更新子行:外键约束失败(todotasks,CONSTRAINT userid外键(userid)参考usersuserid)删除时不采取任何措施,而更新时不采取任何措施)

package sample.Database;

public class Const {

    public static final String USERS_TABLE = "users";
    public static final String TASKS_TABLE = "tasks";

    //USERS Table Column Names
    public static final String USERS_USERID = "userid";
    public static final String USERS_FIRSTNAME = "firstname";
    public static final String USERS_LASTNAME = "lastname";
    public static final String USERS_PASSWORD = "password";
    public static final String USERS_USERNAME = "username";
    public static final String USERS_LOCATION = "location";
    public static final String USERS_GENDER = "gender";

    //TASKS Table Column Names
    public static final String TASKS_ID = "taskid";
    public static final String TASKS_TASK = "task";
    public static final String TASKS_DESCRIPTION = "description";
    public static final String TASKS_DATE = "datecreated";
}

    public void inserTask(Task task){

        String insert = "INSERT INTO "+Const.TASKS_TABLE + "("+Const.USERS_USERID+","
        +Const.TASKS_DATE + ","+Const.TASKS_DESCRIPTION+","+Const.TASKS_TASK + ")"
                + "VALUES(?,?,?,?)";

        try {
            try {
                PreparedStatement preparedStatement = getDbConnection().prepareStatement(insert);

                preparedStatement.setInt(1,task.getUserID());
                preparedStatement.setTimestamp(2,task.getDatecreated());
                preparedStatement.setString(3,task.getDescription());
                preparedStatement.setString(4,task.getTask());


                preparedStatement.executeUpdate();

            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

error occur when I press saveTaskButton

    saveTaskButton.setOnAction(event ->{
            Task task = new Task();

            Calendar calendar = Calendar.getInstance();

            java.sql.Timestamp timeStamp = new java.sql.Timestamp(calendar.getTimeInMillis());

            String tastText= taskField.getText().trim();
            String taskDescription = taskField.getText().trim();
            if(!tastText.equals("") || !taskDescription.equals("")){

            task.setDatecreated(timeStamp);
            task.setDescription(taskDescription);
            task.setTask(tastText);
            task.setUserID(getUserID());
            }else{

                System.out.println("NOthing added!");
            }

            databaseHandler.inserTask(task);
            System.out.println("Task created successfully");
        });

添加架构 tasks

users

1 个答案:

答案 0 :(得分:0)

我为我的课堂创造了静态价值,并能够解决问题。 将该值传递给

task.setUserID(AddItem.UserID);