我是新来的SQL和一般编程,所以如果答案是明显的,请耐心等待。我有一张名为“门票”的表,其中包含主键ticket_id。我还有另一个名为“contact_info”的表,它存储了创建票的人的联系信息。在这个表中,ticket_id是一个叫做ticket_number的外键。用户通过GUI插入票证,并且ticket_number在数据库中自动递增。如何选择ticket_number并将其插入到包含创建该票证的人的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!");
非常感谢!这是非常有帮助和容易理解的 – shaydoe
您能否给我一个看起来像您所描述的交易的例子? (使用捆绑的插入) – shaydoe
事务通常与 – GHWP