PHP PDO事務提交mysql語句

來源:互聯網
上載者:User
$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;   

最終還是使用預存程序來執行事務,要方便的多
  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.