search
HomeDatabaseMysql TutorialMYSQL--事务处理_MySQL

MYSQL--事务处理_MySQL

Jun 01, 2016 pm 01:35 PM
people managementDatabase operationsmanagement system

bitsCN.com

MYSQL--事务处理

 

事务处理在各种管理系统中都有着广泛的应用,比如人员管理系统,很多同步数据库操作大都需要用到事务处理。比如说,在人员管理系统中,你删除一个人员,你即需要删除人员的基本资料,也要删除和该人员相关的信息,如信箱,文章等等,这样,这些数据库操作语句就构成一个事务!  www.bitsCN.com  

     删除的SQL语句

delete from userinfo where ~~~

delete from mail where ~~

delete from article where~~

~~  www.bitsCN.com  

   如果没有事务处理,在你删除的过程中,假设出错了,只执行了第一句,那么其后果是难以想象的!

但用事务处理。如果删除出错,你只要rollback就可以取消删除操作(其实是只要你没有commit你就没有确实的执行该删除操作)

 

   一般来说,在商务级的应用中,都必须考虑事务处理的!

 

查看inodb信息

      shell> /usr/local/mysql -u root -p

      mysql> show variables like "have_%"

系统会提示:

+------------------+-------+

| Variable_name     | Value |

+------------------+-------+

| have_bdb          | YES    |

| have_crypt        | YES    |

| have_innodb       | YES    |

| have_isam         | YES    |

| have_raid         | YES    |

| have_symlink      | YES    |

| have_openssl      | NO     |

| have_query_cache | YES    |

+------------------+-------+

8 rows in set (0.05 sec)

如果是这样的,那么我们就可以创建一张支持事务处理的表来试试了。

 

MYSQL的事务处理功能!

 

作者:Feifengxlq   Email:feifengxlq@sohu.com

一直以来我都以为MYSQL不支持事务处理,所以在处理多个数据表的数据时,一直都很麻烦(我是不得不将其写入文本文件,在系统重新加载得时候才写入数据库以防出错)~今天发现MYSQL数据库从4.1就开始支持事务功能,据说5.0将引入存储过程^_^

      先简单介绍一下事务吧!事务是DBMS得执行单位。它由有限得数据库操作序列组成得。但不是任意得数据库操作序列都能成为事务。一般来说,事务是必须满足4个条件(ACID)

      原子性(Autmic):事务在执行性,要做到“要么不做,要么全做!”,就是说不允许事务部分得执行。即使因为故障而使事务不能完成,在rollback时也要消除对数据库得影响!

     一致性(Consistency):事务得操作应该使使数据库从一个一致状态转变倒另一个一致得状态!就拿网上购物来说吧,你只有即让商品出库,又让商品进入顾客得购物篮才能构成事务!

     隔离性(Isolation):如果多个事务并发执行,应象各个事务独立执行一样!

     持久性(Durability):一个成功执行得事务对数据库得作用是持久得,即使数据库应故障出错,也应该能够恢复!

   

   MYSQL的事务处理主要有两种方法。

   1、用begin,rollback,commit来实现

        begin 开始一个事务

        rollback 事务回滚

        commit  事务确认

    2、直接用set来改变mysql的自动提交模式

       MYSQL默认是自动提交的,也就是你提交一个QUERY,它就

直接执行!我们可以通过

      set autocommit=0   禁止自动提交

      set autocommit=1 开启自动提交

   来实现事务的处理。

但注意当你用 set autocommit=0 的时候,你以后所有的SQL都将

做为事务处理,直到你用commit确认或rollback结束,注意当你结

束这个事务的同时也开启了个新的事务!按第一种方法只将当前的作为一个事务!

个人推荐使用第一种方法!

   MYSQL中只有INNODB和BDB类型的数据表才能支持事务处理!

其他的类型是不支持的!(切记!)

 

下次有空说下MYSQL的数据表的锁定和解锁!

 

       MYSQL5.0 WINXP下测试通过~   ^_^

 

mysql> use test;

Database changed

mysql> CREATE TABLE `dbtest`(

     -> id int(4)

     -> ) TYPE=INNODB;

Query OK, 0 rows affected, 1 warning (0.05 sec)

 

mysql> select * from dbtest

     -> ;

Empty set (0.01 sec)

 

mysql> begin;

Query OK, 0 rows affected (0.00 sec)

 

mysql> insert into dbtest value(5);

Query OK, 1 row affected (0.00 sec)

 

mysql> insert into dbtest value(6);

Query OK, 1 row affected (0.00 sec)

 

mysql> commit;

Query OK, 0 rows affected (0.00 sec)

 

mysql> select * from dbtest;

+------+

| id    |

+------+

|     5 |

|     6 |

+------+

2 rows in set (0.00 sec)

 

mysql> begin;

Query OK, 0 rows affected (0.00 sec)

 

mysql> insert into dbtest values(7);

Query OK, 1 row affected (0.00 sec)

 

mysql> rollback;

Query OK, 0 rows affected (0.00 sec)

 

mysql> select * from dbtest;

+------+

| id    |

+------+

|     5 |

|     6 |

+------+

2 rows in set (0.00 sec)

 

mysql>

 

*************************************************

 

[PHP]

function Tran( $sql ) {

         $judge = 1;

         mysql_query('begin');

         foreach ($sql as $v) {

                 if ( !mysql_query($v) ) {

                         $judge = 0;

                 }

         }

         if ($judge == 0) {

                 mysql_query('rollback');

                 return false;

         }

         elseif ($judge == 1) {

                 mysql_query('commit');

                 return true;

         }

}

[/PHP]

 

************************************************

 

$handler=mysql_connect("localhost","root","");

mysql_select_db("task");

mysql_query("SET AUTOCOMMIT=0");//设置为不自动提交,因为MYSQL默认立即执行

mysql_query("BEGIN");//开始事务定义

if(!mysql_query("insert into trans (id) values('2')"))

{

mysql_query("ROOLBACK");//判断当执行失败时回滚

}

if(!mysql_query("insert into trans (id) values('4')"))

{

mysql_query("ROOLBACK");//判断执行失败回滚

}

mysql_query("COMMIT");//执行事务

mysql_close($handler);

?>

bitsCN.com
Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
When should you use a composite index versus multiple single-column indexes?When should you use a composite index versus multiple single-column indexes?Apr 11, 2025 am 12:06 AM

In database optimization, indexing strategies should be selected according to query requirements: 1. When the query involves multiple columns and the order of conditions is fixed, use composite indexes; 2. When the query involves multiple columns but the order of conditions is not fixed, use multiple single-column indexes. Composite indexes are suitable for optimizing multi-column queries, while single-column indexes are suitable for single-column queries.

How to identify and optimize slow queries in MySQL? (slow query log, performance_schema)How to identify and optimize slow queries in MySQL? (slow query log, performance_schema)Apr 10, 2025 am 09:36 AM

To optimize MySQL slow query, slowquerylog and performance_schema need to be used: 1. Enable slowquerylog and set thresholds to record slow query; 2. Use performance_schema to analyze query execution details, find out performance bottlenecks and optimize.

MySQL and SQL: Essential Skills for DevelopersMySQL and SQL: Essential Skills for DevelopersApr 10, 2025 am 09:30 AM

MySQL and SQL are essential skills for developers. 1.MySQL is an open source relational database management system, and SQL is the standard language used to manage and operate databases. 2.MySQL supports multiple storage engines through efficient data storage and retrieval functions, and SQL completes complex data operations through simple statements. 3. Examples of usage include basic queries and advanced queries, such as filtering and sorting by condition. 4. Common errors include syntax errors and performance issues, which can be optimized by checking SQL statements and using EXPLAIN commands. 5. Performance optimization techniques include using indexes, avoiding full table scanning, optimizing JOIN operations and improving code readability.

Describe MySQL asynchronous master-slave replication process.Describe MySQL asynchronous master-slave replication process.Apr 10, 2025 am 09:30 AM

MySQL asynchronous master-slave replication enables data synchronization through binlog, improving read performance and high availability. 1) The master server record changes to binlog; 2) The slave server reads binlog through I/O threads; 3) The server SQL thread applies binlog to synchronize data.

MySQL: Simple Concepts for Easy LearningMySQL: Simple Concepts for Easy LearningApr 10, 2025 am 09:29 AM

MySQL is an open source relational database management system. 1) Create database and tables: Use the CREATEDATABASE and CREATETABLE commands. 2) Basic operations: INSERT, UPDATE, DELETE and SELECT. 3) Advanced operations: JOIN, subquery and transaction processing. 4) Debugging skills: Check syntax, data type and permissions. 5) Optimization suggestions: Use indexes, avoid SELECT* and use transactions.

MySQL: A User-Friendly Introduction to DatabasesMySQL: A User-Friendly Introduction to DatabasesApr 10, 2025 am 09:27 AM

The installation and basic operations of MySQL include: 1. Download and install MySQL, set the root user password; 2. Use SQL commands to create databases and tables, such as CREATEDATABASE and CREATETABLE; 3. Execute CRUD operations, use INSERT, SELECT, UPDATE, DELETE commands; 4. Create indexes and stored procedures to optimize performance and implement complex logic. With these steps, you can build and manage MySQL databases from scratch.

How does the InnoDB Buffer Pool work and why is it crucial for performance?How does the InnoDB Buffer Pool work and why is it crucial for performance?Apr 09, 2025 am 12:12 AM

InnoDBBufferPool improves the performance of MySQL databases by loading data and index pages into memory. 1) The data page is loaded into the BufferPool to reduce disk I/O. 2) Dirty pages are marked and refreshed to disk regularly. 3) LRU algorithm management data page elimination. 4) The read-out mechanism loads the possible data pages in advance.

MySQL: The Ease of Data Management for BeginnersMySQL: The Ease of Data Management for BeginnersApr 09, 2025 am 12:07 AM

MySQL is suitable for beginners because it is simple to install, powerful and easy to manage data. 1. Simple installation and configuration, suitable for a variety of operating systems. 2. Support basic operations such as creating databases and tables, inserting, querying, updating and deleting data. 3. Provide advanced functions such as JOIN operations and subqueries. 4. Performance can be improved through indexing, query optimization and table partitioning. 5. Support backup, recovery and security measures to ensure data security and consistency.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools