我必須從jsp表單插入值到數據庫表和我需要插入2個不同表中的兩列的值相同的表。如何在mysql中編寫單個查詢以進行多個數據操作?
下面是代碼:
public class ForgotPassWordDAO {
private DataSource dataSource;
public void setDataSource(DataSource dataSource) {
this.dataSource = dataSource;
}
Connection conn = null;
PreparedStatement ps = null;
ResultSet rs = null;
public void createSecretQnA(ForgotPassWord forgotPassWord) {
String sql = "INSERT INTO forgotpassword (PwdId,SecretQuestion1,SecretAnswer1,SecretQuestion2,SecretAnswer2)VALUES(?,?,?,?,?)"; // Here am inserting form values to database.
String sql1="INSERT INTO forgotpassword (CustId) SELECT CustId FROM signup";// Here am trying to get value from another table and insert
String sql2="INSERT INTO forgotpassword (LoginId) SELECT LoginId FROM login"; // Here am trying to get value from another table and insert
Connection conn = null;
try {
conn = dataSource.createConnection();
PreparedStatement ps = conn.prepareStatement(sql);
PreparedStatement ps1 = conn.prepareStatement(sql1);
PreparedStatement ps2 = conn.prepareStatement(sql2);
ps.setInt(1, forgotPassWord.getId());
ps.setString(2, forgotPassWord.getSq1());
ps.setString(3, forgotPassWord.getAnSq1());
ps.setString(4, forgotPassWord.getSq2());
ps.setString(5, forgotPassWord.getAnSq2());
ps.executeUpdate();
ps1.executeUpdate();
ps2.executeUpdate();
ps.close();
} catch (SQLException e) {
throw new RuntimeException(e);
}
catch (NullPointerException e1){
}
finally {
if (conn != null) {
try {
conn.close();
} catch (SQLException e) {
}
}
}
}
但是每個的executeUpdate()其遞增,並從表格中的值被存儲在一行和下一行中從註冊和登錄表中的值越來越存儲。如何使所有這些被存儲在一行中?任何幫助表示讚賞。
如何通過選擇查詢獲取custId和loginId,然後只插入一個插入查詢? – irene 2014-09-19 08:23:31
@Narmer那麼該如何解決? – user3349720 2014-09-19 08:25:45
@irene你可以讓我知道如何做到這一點? – user3349720 2014-09-19 08:26:37