mysql - 如何使用 shell 模拟并发 SQL 命令

标签 mysql shell

我有一张 table ,例如股票:

SELECT * FROM stock;
+------------+----------+
| product_id | quantity |
+------------+----------+
|          1 |      100 |
+------------+----------+

我想模拟并发提交订单并同时减少库存:

UPDATE store SET quantity = quantity-${count} WHERE product_id = ${product_id}

我想知道这个 SQL 是否是线程安全的。我只是使用下面的方式来模拟并发操作:

for ((i=0; i<100; i++))
do
    mysql -uroot -p123456 test -e "update stock set quantity=quantity-1 where product_id = 1" >/dev/null &
done

然后检查最终数量是否为0。 我想知道这种方式是否正确?也就是说,它是否会像 100 个用户同时提交订单一样正确发送并发 SQL 命令?

最佳答案

这是一个很好的方法:

for ((i=0; i<100; i++)); do
    mysql -uroot -p123456 test -e "update stock set quantity=quantity-1 where product_id = 1" >/dev/null &
done

wait

您需要在最后wait 使其在作业仍在运行时不退出。

关于mysql - 如何使用 shell 模拟并发 SQL 命令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34836976/

相关文章:

shell - 检测脚本是否源自 "/bin/sh"

linux - 在linux中的多个目录中的文件上运行shell脚本

php - move_uploaded_file 不工作

linux - BASH:如何监视脚本执行失败

php - 基本准备语句不插入

PHP MySQL 插入/选择多个一对多

shell - 如何确定HDFS中的文件夹是否存在以及其中是否有文件?

linux - 如何在 bash 脚本中传递两个参数或参数

mysql - 为什么我的自定义 SQL 查询(在 Tableau 之外工作正常)在 Tableau 中失败?

c++ - MySQL C++ 连接器 Unresolved 依赖项 (VS 2015)