会计用mysql,MySQL会计应用交易

I have a table like the following:

transaction_id

user_id

other_user_id

trans_type

amount

This table is used to maintain the account transactions for a finance type app.

Its double entry accounting so a transfer from User A to B would insert two rows into the table looking like.

1, A, B, Sent, -100

1, B, A, Received, 100

The balance on any account is calculated by summing up the transactions for that account.

For example:

select sum(amount) from transactions where user_id=A

What is the best way to lock down transferring of funds? My current code looks like:

Start Transaction

Debit the sender's account

check the balance of the sender's account

if new balance is negative then the sender didn't have enough money and rollback

if the balance is positive then credit the receiver and commit

This seems not to be working exactly as expected. I see a lot of examples online about transactions that say basically: start, debit sender, credit receiver, commit. But what is the best way to check the sender's balance in between?

I have transactions getting through that shouldn't. Say a user has a balance of 3K and two transactions come in at exactly the same time for 3K, both of these are getting through when only one should.

Thank you

解决方案

Are you using InnoDB tables or MyISAM tables? MySQL doesn't support transactions on MyISAM tables (but it won't give you an error if you try to use them). Also, make sure your transaction isolation level is set appropriately, it should be SERIALIZABLE which is not the default for MySQL.

This article has a good example that explains the impact of the different isolation levels using an example very similar to yours.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值