簡體   English   中英

使用單個“更新” JButton將測試表的auto_increment值插入到得分表中

[英]Insert auto_increment value of the test table to the score table table using a single “update” JButton

Java應用程序可插入學生分數和參加的考試類型
在此處輸入圖片說明

MySQL表測試表和分數表
在此處輸入圖片說明

我需要單擊“更新”按鈕來更新兩個表。 我如何將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的值並將其插入到scores表中,並使用以下代碼。

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的兩個連接代碼都在“ update”操作偵聽器中。

這樣做的目的是針對不同的主題(具有連續的評估和考試)和分數構建一個簡單的學生成績檢查器應用程序。 我也歡迎任何有關構建更好的MySQL數據庫的建議

在並發的情況下,查詢生成的ID的方法可能並不總是有效,例如,多個用戶同時使用該應用程序。 它取決於配置的並發隔離級別。 如果兩個事務都先插入測試,然后都查詢ID,則一個事務將獲得另一事務插入的測試的ID。

這篇文章中回答了如何獲取生成的ID。 這些是根據帖子執行的主要操作:

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

我不認識有關您的數據庫架構的任何問題,但是如果您使用了Hibernate之類的ORM框架,則無需考慮如何獲取ID。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM