【发布时间】:2023-03-17 00:27:01
【问题描述】:
我是 SQL 和一般编程的新手,所以如果这个问题的答案很明显,请多多包涵。我有一个名为“tickets”的表,其中包含主键ticket_id。我还有另一个名为“contact_info”的表,它存储创建票证的人的联系信息。在这个表中,ticket_id 是一个名为ticket_number 的外键。用户通过 GUI 插入票据,并且票据编号在数据库中自动递增。如何选择ticket_number 并将其插入到包含创建该ticket 的人的contact_info 的行中?
这是现在的代码,它并没有达到我的预期:
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!");
【问题讨论】: