简体   繁体   English

如何将一个表的主键值插入另一个表的外键列?

[英]How do I insert primary key value from one table to foreign key column in another?

I am new to SQL and programming in general so please bear with me if the answer to this is obvious. 我一般都不熟悉SQL和编程,因此,如果答案很明显,请与我联系。 I have one table called "tickets" which contains the primary key ticket_id. 我有一个名为“ tickets”的表,其中包含主键ticket_id。 I also have another table called "contact_info" which stores the contact information of the person who created the ticket. 我还有另一个名为“ contact_info”的表,该表存储了创建票证的人的联系信息。 In this table, ticket_id is a foreign key called ticket_number. 在此表中,ticket_id是一个名为ticket_number的外键。 The user inserts tickets through a GUI and the ticket_number is auto incremented in the database. 用户通过GUI插入票证,ticket_number在数据库中自动增加。 How do I select the ticket_number and insert it into the row that contains the contact_info of the person who created that ticket? 如何选择ticket_number并将其插入包含创建该ticket的人的contact_info的行?

This is the code right now and it does not do what I expect it to: 这是现在的代码,它没有达到我的期望:

try{
              //Open a connection
              System.out.println("Connecting to a selected database...");
              this.connection = DriverManager.getConnection(url, username, password);
              System.out.println("Connected database successfully...");

              //Execute a query
              System.out.println("Inserting records into the table...");
              PreparedStatement pstmt = connection.prepareStatement(" INSERT INTO s_fuse_ticket_table "
                              + " (summary, status, severity, classification, type, internal_notes, description, assignees) "
                              + " VALUES (?, ?, ?, ?, ?, ?, ?, ?)");

                          if(summary.getText().equals("")){
                              throw new SQLException("Summary cannot be blank");
                          }
                          pstmt.setString(1, summary.getText());
                  pstmt.setString(2, status.getSelectionModel().getSelectedItem().toString());
                  pstmt.setString(3, severity.getSelectionModel().getSelectedItem().toString());
                          if(classification.getSelectionModel().getSelectedItem().toString().equals("Make a Selection")){
                              throw new SQLException("Please select a classification");
                          }
                          pstmt.setString(4, classification.getSelectionModel().getSelectedItem().toString());
                          if(type.getSelectionModel().getSelectedItem().toString().equals("Make a Selection")){
                              throw new SQLException("Please select a type");
                          }
                          pstmt.setString(5, type.getSelectionModel().getSelectedItem().toString());
                          pstmt.setString(6, internalNotes.getText());
                          pstmt.setString(7, description.getText());
                          pstmt.setString(8, assignee.getSelectionModel().getSelectedItem().toString());
                  pstmt.executeUpdate();

                          //Execute a query
                        System.out.println("Inserting records into the table...");
                        PreparedStatement pstmt2 = connection.prepareStatement(" INSERT INTO s_fuse_contact_info_table "
                              + " (ticket_number, email, last_name, first_name) "
                              + " VALUES (?, ?, ?, ?)");

                          pstmt2.setString(1, ("SELECT ticket_id FROM s_fuse_ticket_table"));
                          /*if(!email.getText().contains("@") && !email.getText().contains(".")){

                          }*/
                          pstmt2.setString(2, email.getText());
                          pstmt2.setString(3, lname.getText());
                          pstmt2.setString(4, fname.getText());
                  pstmt2.executeUpdate();
           }catch(SQLException se){
              //Handle errors for JDBC
              se.printStackTrace();
           }catch(Exception e){
              //Handle errors for Class.forName
              e.printStackTrace();
           }finally{
              //finally block used to close resources
              try{
                 if(stmt!=null)
                 {
                    connection.close();
                 }
              }catch(SQLException se){
              }// do nothing
              try{
                 if(connection!=null)
                 {
                    connection.close();
                 }
              }catch(SQLException se){
                 se.printStackTrace();
              }//end finally try
           }//end try
           System.out.println("Goodbye!");

Different DBMS' have different ways to do this - refer to this question for a pretty comprehensive list. 不同的DBMS有不同的方法来执行此操作-有关完整列表,请参阅此问题

Another way is to use transactions. 另一种方法是使用事务。 With an MVCC DBMS in a suitable isolation level (repeatable read or serializable), when you start a new connection you will have your own view of the db, so you can INSERT INTO the main table, then SELECT the latest row that matches your insert and be confident that it belongs to you. 使用处于适当隔离级别(可重复读取或可序列化)的MVCC DBMS,启动新连接时,您将拥有自己的db视图,因此您可以将INSERT INTO主表,然后SELECT与插入匹配的最新行并确信它属于您。 It's a good idea to bundle inserts like this together anyway, as it prevents any inconsistent data getting into the system - just make sure you commit afterward! 最好将这样的插入捆绑在一起,因为这样可以防止任何不一致的数据进入系统-只需确保事后提交即可!

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何将数据插入一个表并获取主键作为外键插入另一个表中? - How do I insert data into one table & get the primary key to insert in another table as a foreign key? 如何将主键作为外键插入另一个表? - How do I insert the primary key to another table as foreign key? 如何将多个不同值从一个表中的一列插入到另一个表中并引用相应的外键? - How do i insert multiple varying values from a column in one table to another table with the corresponding foreign key referenced? 如何将数据插入表中,其中一个值应该是另一个表的外键? - How do I insert data into a table where one of the values should be a foreign key from another table? MySQL中如何将主表的Primary Key值插入到子表的Foreign Key列? - How to insert Primary Key value of the primary table to the Foreign Key column of the child table in MySQL? 如何从两个表中查询匹配表中的外键和另一个表中的主键 - How do I query from two tables matching the foreign key from table with the primary key from another 在 SQL 中是否有任何约束,我在其中添加一个作为外键的值到一个表,它从另一个表中删除该值(主键)? - Is there any constraint in SQL where I add a value that is a foreign key to one table, it removes that value(primary key) from another table? MySQL - 将主键从一个表插入另一个表(外键) - MySQL - Inserting Primary Key from one table to another (Foreign Key) Java/Mysql 从一个表中选择主键值并将它们作为外键插入到另一个表中 - Java/Mysql Selecting Primary Key values from one table and Insert them to another table as Foreign Keys 如何从下拉列表中捕获主键并插入为另一个表的外键? - How to capture primary key from drop down and insert as foreign key of another table?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM