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 的连接代码都在 “更新” Action 监听器。
这样做的目的是为不同的科目(包括连续评估和考试)和分数构建一个简单的学生成绩检查应用程序。我也欢迎任何关于构建更好的 MySQL 数据库的建议
最佳答案
在并发情况下,查询生成的 ID 的方法可能并不总是有效,例如多个用户同时使用该应用程序。这取决于配置的并发隔离级别。如果两个事务首先都插入测试,然后都查询 ID,一个事务将获取另一个事务插入的测试的 ID。
如何获取生成的 ID 在 this post 中有解答。根据帖子,这些是要做的主要事情:
PreparedStatement statement = connection.prepareStatement(SQL_INSERT, Statement.RETURN_GENERATED_KEYS);
...
ResultSet generatedKeys = statement.getGeneratedKeys()
我不认为您的数据库模式有任何问题,但如果您使用像 Hibernate 这样的 ORM 框架,您就不必考虑如何获取 ID。
关于java - 使用单个 "update"JButton 将测试表的 auto_increment 值插入到分数表表中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39064381/