我有2个表,第一个表是具有所有交易记录的交易表,第二个表是具有所有交易金额总计的储蓄表。
INSERT INTO `groupsavings`.`transactions`
(`transactions_id`, `shareholder_id`, `transactions_type`,
`transactions_date`, `ammount`, `pool`)
VALUES (NULL, '1', 'credit', '2019-01-01', '100', 'poolone');
INSERT INTO `groupsavings`.`transactions`
(`transactions_id`, `shareholder_id`, `transactions_type`,
`transactions_date`, `ammount`, `pool`)
VALUES (NULL, '1', 'credit', '2019-01-01', '50', 'poolone');
UPDATE `groupsavings`.`saving_pool`
SET `pool_value` = '100'
WHERE `saving_pool`.`Pool_name` = 'poolone';
UPDATE `groupsavings`.`saving_pool`
SET `pool_value` = '150'
WHERE `saving_pool`.`Pool_name` = 'poolone';
我希望储蓄表在插入到交易表中时累积地添加到储蓄表中。
答案 0 :(得分:-1)
我猜您想用交易表中当前金额的总和自动更新储蓄表。
假设您这样命名数据库连接变量(Connection con,PreparedStatement pst,ResultSet rs),您可以尝试此方法
public void insertt(){
String trans_id = "";
String share_id = "";
String trans_type = "";
String trans_date = "";
String amt = "";
String poolname = "";
try{
String sql = " INSERT INTO groupsavings.transactions (transactions_id, shareholder_id, transactions_type, transactions_date, ammount, pool)VALUES (?, ?, ?, ?, ?, ?)";
pst = con.prepareStatement(sql);
pst.setString(1, trans_id);
pst.setString(2, share_id);
pst.setString(3, trans_type);
pst.setString(4, trans_date);
pst.setString(5, amt);
pst.setString(6, poolname);
pst.execute();
String sql2 = "select sum(ammount) from groupsavings.transactions WHERE saving_pool.pool_name = ’"+poolname+"' ";
pst = con.prepareStatement(sql2);
rs = pst.executeQuery();
int sum = 0;
while(rs.next()){
sum = rs.getInt(0);
String newpool = String.valueOf(sum);
}
String sql3 ="UPDATE groupsavings.saving_pool SET pool_value = ’"+newpool+"' WHERE saving_pool.pool_name =’"+poolname+"' ";
pst = con.prepareStatement(sql3);
pst.execute();
}
catch(SQLException e){}
}