我是新來的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