$db = new PDO ( 'mysql:host=' . $cfg ['hostanme'] . ';dbname=' . $cfg ['dbname'], $cfg ['username'], $cfg ['password'] );$db->exec ( "set character_set_client = utf8" );$db->exec ( "SET character_set_results =utf8" );$db->exec ( "SET character_set_connection = utf8" );$db->query ( "BEGIN" ); // 事務開始$calories ="sa阿薩德";$sth = $db->prepare(' INSERT INTO `test_user` values ( null,1, :calories);');$sth->execute(array(':calories' => $calories ));$sths = $db->prepare(' INSERT INTO `test_users` values ( null,1, :calories);');$sths->execute(array(':calories' => $calories )); //故意寫錯的$lastid = $db->lastInsertId();$sd = $sth->rowCount();
想問一下,通過這種方式處理事務,是不是每次只能執行一條sql,然後在判斷? 如果我SQL語句很多,例如10條以上,那不是要寫10多個,判斷10多次? 有沒有一次可以執行多條sql的事務? 另外,mysql 中,預存程序怎麼寫事務?PHP如何調用?
回複討論(解決方案)
DROP PROCEDURE IF EXISTS pro_rep_shadow_rs;create procedure pro_rep_shadow_rs(out rtn int) begin -- 如果出現異常,會自動處理並rollback declare exit handler for sqlexception ROLLBACK ; -- 啟動事務 start transaction; insert into test_user values(NULL,1,'啊是大三的');insert into test_user VALUES(NULL,23,'sdsd',ss); --故意寫錯的 -- 運行沒有異常,提交事務 commit; -- 設定傳回值為1 set rtn=1; end;
最終還是使用預存程序來執行事務,要方便的多