thinkphpÔõÑù×öÊÂÎï
thinkphp ÊÇÒ»¿îÊ¢ÐÐµÄ php ¿ò¼Ü£¬ËüÌṩÁËÒ»ÖÖÀû±ãµÄ·½·¨À´¿ª·¢ web Ó¦ÓóÌÐò£¬²¢ÌṩÁËһϵÁÐÓÐÓõĹ¦Ð§£¬ÀýÈ磺·ÓÉ¡¢Êý¾Ý¿â»á¼û¡¢Ä£°åÒýÇæµÈµÈ¡£ÔÚÕâƪÎÄÕÂÖУ¬ÎÒÃǽ«ÏÈÈÝÔõÑùÔÚ thinkphp ÖÐʹÓÃÊÂÎñ¡£
Ò»¡¢Ê²Ã´ÊÇÊÂÎñ£¿
ÔÚ¹ØϵÐÍÊý¾Ý¿âÖУ¬A ×é SQL ²Ù×÷¿ÉÒÔ±»¿´×÷ÊÇÒ»¸öÕûÌ壬¶øÕâ¸öÕûÌåµÄÖ´ÐÐҪôËùÓÐÀֳɣ¬ÒªÃ´ËùÓÐʧ°Ü¡£ÕâÖÖÐÐΪ±»³ÆΪÊÂÎñ¡£ÊÂÎñ±£»¤ÁËÄãµÄÊý¾Ý¿âÃâÊÜÊý¾Ý·×ÆçÖÂÐÔµÄÍþв£¬Í¬Ê±Ò²ÔÊÐíÄãÔÚ·ºÆð¹ýʧʱ»Ø¹öÄãµÄ²Ù×÷¡£
¶þ¡¢ÔõÑùÔÚ ThinkPHP ÖÐʹÓÃÊÂÎñ£¿
ÔÚ ThinkPHP ÖУ¬ÎÒÃÇ¿ÉÒÔͨ¹ýÒÔϼ¸¸ö°ì·¨À´Ê¹ÓÃÊÂÎñ£º
Á¬Ã¦Ñ§Ï°¡°PHPÃâ·ÑѧϰÌõ¼Ç£¨ÉîÈ룩¡±£»
»ñÈ¡Êý¾Ý¿âÅþÁ¬
ʹÓÃÊÂÎñ֮ǰ£¬ÎÒÃÇÐèÒª»ñÈ¡Êý¾Ý¿âÅþÁ¬¡£ÔÚ ThinkPHP ÖУ¬ÎÒÃÇ¿ÉÒÔͨ¹ýÒÔÏ·½·¨À´»ñÈ¡Êý¾Ý¿âÅþÁ¬£º
$db=Db::connect();
µÇ¼ºó¸´ÖÆ
×îÏÈÊÂÎñ
»ñÈ¡Êý¾Ý¿âÅþÁ¬Ö®ºó£¬ÎÒÃÇÐèҪŲÓà beginTransaction() ÒªÁìÀ´×îÏÈÒ»¸öÊÂÎñ¡£
$db->startTrans();
µÇ¼ºó¸´ÖÆ
Ö´ÐÐ SQL ²Ù×÷
ÔÚÊÂÎñ×îÏÈÖ®ºó£¬ÎÒÃÇ¿ÉÒÔƾ֤Õý³£µÄ·½·¨À´Ö´ÐÐ SQL ²Ù×÷¡£
$db->execute("INSERT INTO users (name, age) VALUES ('Tom', '18')"); $db->execute("UPDATE users SET age = '20' WHERE name = 'Tom'");
µÇ¼ºó¸´ÖÆ
Ìá½»»ò»Ø¹öÊÂÎñ
ÔÚËùÓÐ SQL ²Ù×÷¶¼Ö´ÐÐÍê±ÏÖ®ºó£¬ÎÒÃÇÐèҪƾ֤ÇéÐÎÀ´Ìá½»»òÕ߻عöÊÂÎñ¡£ÈôÊÇËùÓвÙ×÷¶¼Íê³É²¢ÇÒûÓз¢Ã÷Èκιýʧ£¬ÎÒÃÇ¿ÉÒÔŲÓà commit() ÒªÁìÀ´Ìá½»ÊÂÎñ¡£
$db->commit();
µÇ¼ºó¸´ÖÆ
ÈôÊÇÖ´ÐÐÀú³ÌÖб¬·¢Á˹ýʧ£¬ÎÒÃÇ¿ÉÒÔŲÓà rollBack() ÒªÁìÍù·µ¹öÊÂÎñ¡£
$db->rollback();
µÇ¼ºó¸´ÖÆ
ÊÍ·ÅÊý¾Ý¿âÅþÁ¬
ÔÚÊÂÎñ¿¢ÊÂÖ®ºó£¬ÎÒÃÇÐèÒªÊÍ·ÅÊý¾Ý¿âÅþÁ¬¡£
$db = null;
µÇ¼ºó¸´ÖÆ
Èý¡¢ÊÂÎñµÄ¹ýʧ´¦Àí
ÔÚÊÂÎñÖ´ÐÐÀú³ÌÖУ¬ÈôÊÇ·ºÆðÁ˹ýʧ£¬ÎÒÃÇÐèÒªÔÊÐí³ÌÐò´¦ÀíÕâЩ¹ýʧ¡£ÔÚ ThinkPHP ÖУ¬ÎÒÃÇ¿ÉÒÔͨ¹ý try-catch Óï¾äÀ´´¦Àí¹ýʧ¡£
try { $db=Db::connect(); $db->startTrans(); //Ö´ÐÐ SQL ²Ù×÷ $db->commit(); } catch (\Exception $e) { $db->rollback(); }
µÇ¼ºó¸´ÖÆ
ÉÏÊö´úÂëÖУ¬ÎÒÃǽ«Õû¸öÊÂÎñµÄ²Ù×÷·ÅÔÚÒ»¸ö try-catch Óï¾ä¿éÄÚÀï¡£ÔÚ try Óï¾ä¿éÄÚÀÎÒÃÇÖ´ÐÐ SQL ²Ù×÷²¢Ìá½»ÊÂÎñ¡£ÈôÊÇÔÚÖ´ÐÐÀú³ÌÖб¬·¢Á˹ýʧ£¬ÎÒÃǾͻáÌøתµ½ catch Óï¾ä¿éÄÚÀ²¢»Ø¹öÕû¸öÊÂÎñ¡£
ËÄ¡¢½áÂÛ
ÊÂÎñÊǹØϵÐÍÊý¾Ý¿âÖеÄÒ»ÖÖºÜÊÇÖ÷ÒªµÄ»úÖÆ£¬Ëü¿ÉÒÔ±£»¤ÄãµÄÊý¾Ý¿âÃâÊÜÊý¾Ý·×ÆçÖÂÐÔµÄÍþв¡£ÔÚ ThinkPHP ÖУ¬ÎÒÃÇ¿ÉÒÔʹÓÃÊÂÎñÀ´Ö´ÐÐÒ»×é SQL ²Ù×÷£¬´Ó¶øÈ·±£ËüÃÇҪôËùÓÐÀֳɣ¬ÒªÃ´ËùÓÐʧ°Ü¡£Òª×¢ÖصÄÊÇ£¬ÊÂÎñµÄʹÓÃÐèÒªÉóÉ÷£¬±ØÐè×Ðϸ´¦Àí¹ýʧ£¬ÒÔÃâ·ºÆðÊý¾Ý·×ÆçÖµÄÇéÐΡ£
ÒÔÉϾÍÊÇthinkphpÔõÑù×öÊÂÎïµÄÏêϸÄÚÈÝ£¬¸ü¶àÇë¹Ø×¢±¾ÍøÄÚÆäËüÏà¹ØÎÄÕ£¡