有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java使用单个“更新”按钮将测试表的自动增量值插入分数表

Java application to insert student scores and type of test taken
enter image description here

MySql tables tests table and scores tables
enter image description here

我需要通过单击“更新”按钮来更新这两个表。我怎样才能拿到考试。在分数上插入测试id值。测试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的值。测试_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数据库的两个连接代码都在 “更新”actionlistener

其目的是为不同科目(连续评估和考试)和分数构建一个简单的学生成绩检查器应用程序。我也欢迎任何关于构建更好的MySQL数据库的建议


共 (1) 个答案

  1. # 1 楼答案

    在并发情况下,查询生成的ID的方法可能并不总是有效,例如多个用户同时使用应用程序。这取决于配置的并发隔离级别。如果两个事务首先都插入测试,然后都查询ID,那么一个事务将获得另一个事务插入的测试的ID

    如何获得生成的ID在this post中给出了答案。根据《华盛顿邮报》的报道,以下是要做的主要事情:

    PreparedStatement statement = connection.prepareStatement(SQL_INSERT,  Statement.RETURN_GENERATED_KEYS);
    ... 
    ResultSet generatedKeys = statement.getGeneratedKeys()
    

    我不知道你的数据库模式有什么问题,但是如果你使用像Hibernate这样的ORM框架,你就不必考虑如何获取ID了