我正在尝试通过点击按钮
来更新学生数据库JButton NewUpdate = new JButton("UPDATE");
NewUpdate.setFont(new Font("Lucida Grande", Font.BOLD, 14));
NewUpdate.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String regNo = RegNoCombo.getSelectedItem().toString();
String subjectCode = SubjectCombo.getSelectedItem().toString(); //gets value selected from subject code JCombobox
double score = Double.parseDouble(scoreTextField.getText().toString());
String testType = AssesmentCombo.getSelectedItem().toString();//gets value selected from assessment code JCombobox
String queryFromScoresTable = "SELECT CONCAT(student_id,subject_id) FROM scores;";
下面的switch语句确定了教师选择的选项。并使用" queryFromScoresTable"从数据库中检索信息。上述
switch (testType) {
case "Class Work":
try {
conn3 = DriverManager.getConnection("jdbc:mysql://localhost:3306/resultchecker_db","%username%","%password%");
ps3 = conn3.prepareStatement(queryFromScoresTable);
rs5 = ps3.executeQuery();
} catch (SQLException e1) {
JOptionPane.showMessageDialog(null, e1);
}
try {
rs5.next();
String compareData = rs5.getString(1);
从DB检索到的查询将转换为带有变量名称的字符串" compareData"
" if"下面的陈述应该检查学生是否" regNo"和" testType"存在,如果是,则通过更新表中的信息来执行该块
if((regNo + subjectCode).equals(compareData)){
String queryUpdateStudRecord = "UPDATE scores SET class_work=? WHERE student_id=? and subject_id = ?;";
conn4 = DriverManager.getConnection("jdbc:mysql://localhost:3306/resultchecker_db","%username%","%password%");
ps4 = conn4.prepareStatement(queryUpdateStudRecord);
ps4.setDouble(1, score);
ps4.setString(2, regNo);
ps4.setString(3, subjectCode);
ps4.execute();
rs5.next();
此外,通过将学生regNo和所选testType的分数插入数据库来执行此块。
}else{
String queryInsertRecord = "INSERT INTO scores(student_id, subject_id, class_work) VALUES (?,?,?)";
conn4 = DriverManager.getConnection("jdbc:mysql://localhost:3306/resultchecker_db","%username%","%password%");
ps4 = conn4.prepareStatement(queryInsertRecord);
ps4.setString(1, regNo);
ps4.setString(2, subjectCode);
ps4.setDouble(3, score);
ps4.execute();
rs5.next();
}
但问题是只有"否则"语句执行时不评估" if"声明,这意味着如果已存在regNo,则无法更新。因为它将返回现有的主键错误。
需要帮助,谢谢你
答案 0 :(得分:0)
不知道为什么if
没有触发,但你只能使用一个查询:
INSERT ...
ON DUPLICATE KEY UPDATE student_id=VALUES(student_id), subject_id=VALUES(subject_id)
然后您无需关心是应该进行更新还是插入 - 让DB自动为您决定。
答案 1 :(得分:0)
小心equals()方法。请尝试调试并查看您的内容(regNo + subjectCode)和compareData。