gpt4 book ai didi

java - 代码或 mysql 数据库中的某个地方出错。获取 java.sql.SQLIntegrityConstraintViolationException

转载 作者:行者123 更新时间:2023-11-29 16:08:41 25 4
gpt4 key购买 nike

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

java.sql.SQLIntegrityConstraintViolationException: Cannot add or update a child row: a foreign key constraint fails (todo.tasks, CONSTRAINT userid FOREIGN KEY (userid) REFERENCES users (userid) ON DELETE NO ACTION ON UPDATE NO ACTION)

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

最佳答案

我为我的类(class)创建了静态值并能够解决问题。将该值传递给

task.setUserID(AddItem.UserID);

关于java - 代码或 mysql 数据库中的某个地方出错。获取 java.sql.SQLIntegrityConstraintViolationException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55497224/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com