Java application to insert student scores and type of test taken
MySql tables tests table and scores tables
我需要通过单击"更新"来更新两个表。按钮。如何将tests.test_id值插入到scores.test_id中。
这是我到目前为止所尝试的内容,但只有测试表才会更新。
String subjectCode = SubjectCombo.getSelectedItem().toString(); //gets value selected from subject code JCombobox
String testType = AssesmentCombo.getSelectedItem().toString();//gets value selected from assesment code JCombobox
ResultSet rst = null;
try {
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/resultchecker_db","edunge","Ihu18om@031988");
st = con.createStatement();
String query4 = "INSERT INTO tests (subject_id, type, test_id) VALUES (?,?,NULL)"; //query to update tests table
ps = con.prepareStatement(query4);
ps.setString(1, subjectCode);
ps.setString(2, testType);
ps.execute();
} catch (SQLException e1) {
JOptionPane.showMessageDialog(null, e1);
}
try {
if (rst.next()){
JOptionPane.showMessageDialog(null, "Student record updated");
}
} catch (HeadlessException e1) {
JOptionPane.showMessageDialog(null, e1);
} catch (SQLException e1) {
JOptionPane.showMessageDialog(null, e1);
}
try {
con.close();
st.close();
rst.close();
} catch (SQLException e1) {
JOptionPane.showMessageDialog(null, e1);
}
//这成功更新了测试表
我还尝试在actionlistener上创建另一个mysql连接,该连接将获取test.test_id的值并将其插入到得分表中,代码如下。
try {
Connection con2 = DriverManager.getConnection("jdbc:mysql://localhost:3306/resultchecker_db","edunge","Ihu18om@031988");
Statement st2 = con2.createStatement();
String query5 = "SELECT test_id FROM tests ORDER BY test_id DESC LIMIT 1;";
rst2 = st2.executeQuery(query5);
} catch (SQLException e1) {
JOptionPane.showMessageDialog(null, e1);
}
try {
while(rst2.next()){
label.setText(rst2.getString(1)); //used a label to see if the auto_increment values is received.
}
} catch (SQLException e1) {
JOptionPane.showMessageDialog(null, e1);
}
MySQL DB的两个连接代码都在 "更新"的ActionListener。
这样做的目的是为不同的科目(连续评估和考试)和分数建立一个简单的学生结果检查器应用程序。我也欢迎任何有关构建更好的MySQL数据库的建议
答案 0 :(得分:0)
查询生成的ID的方法在并发的情况下可能并不总是有效,例如:多个用户同时使用该应用程序。它取决于配置的并发隔离级别。如果两个事务首先插入测试然后都查询ID,则一个事务将获得另一个事务插入的测试的ID。
如何获取生成的ID将在this post中得到解答。根据帖子,这些是要做的主要事情:
PreparedStatement statement = connection.prepareStatement(SQL_INSERT, Statement.RETURN_GENERATED_KEYS);
...
ResultSet generatedKeys = statement.getGeneratedKeys()
我不承认有关您的数据库架构的任何问题,但如果您使用像Hibernate这样的ORM框架,则不必考虑如何获取ID。