SQL与事务

SQL原生语句

  1. // 增删改查操作
  2. $result = Db::query('insert into user(name, sex,description, age) values("' . $name . '", 1, "xxxx", 99)')->getResult();
  3. $result = Db::query('delete from user where id=' . $id)->getResult();
  4. $result = Db::query('update user set name="' . $name . '" where id=' . $id)->getResult();
  5. $result = Db::query('select * from user where id=' . $id)->getResult();
  6. // 参数绑定
  7. $result = Db::query('select * from user where id=:id and name=:name', ['id' => $id, ':name'=>'name'])->getResult();
  8. $result2 = Db::query('select * from user where id=? and name=?', [$id, 'name'])->getResult();

事务

开启事务后,事务之间的所有操作都是同一个连接,注意不能使用并发操作。

  1. Db::beginTransaction();
  2. $user = new User();
  3. $user->setName('name');
  4. $user->setSex(1);
  5. $user->setDesc('this my desc');
  6. $user->setAge(mt_rand(1, 100));
  7. $userId = $user->save()->getResult();
  8. $count = new Count();
  9. $count->setUid($userId);
  10. $count->setFollows(mt_rand(1, 100));
  11. $count->setFans(mt_rand(1, 100));
  12. $countId = $count->save()->getResult();
  13. Db::commit();
  14. //Db::rollback();