PHP and MYSQL transaction processing

PHP and MYSQL transaction processing

 

/*
There are two main methods of MYSQL transaction processing.
1. Use begin, rollback, commit to realize begin
, start a transaction
rollback, transaction rollback , commit
transaction confirmation implement! We can disable auto-commit by set autocommit=0 and enable auto-commit to realize transaction processing. When you use set autocommit=0, all your future SQL will be processed as a transaction until you confirm with commit or end with rollback. Note that when you end this transaction you also start a new one! According to the first method only the current as a transaction! Personally recommend using the first method! Only INNODB and BDB data tables in MYSQL can support transaction processing! Other types are not supported! ***: The default engine of the general MYSQL database is MyISAM, which does not support transactions! If you want MYSQL to support transactions, you can manually modify it yourself: the method is as follows: 1. Modify the c:\appserv\mysql\my.ini file, find skip-InnoDB, add # in front, and save the file. 2. Enter in the operation: services.msc, restart the mysql service.












3. Go to phpmyadmin, mysql->show engines; (or execute mysql->show variables like 'have_%'; ), check that InnoDB is YES, which means that the database supports InnoDB.
It also means that transaction transactions are supported.
4. When creating a table, you can select the InnoDB engine for the Storage Engine. If it is a previously created table, you can use mysql->alter table table_name type=InnoDB;
or mysql->alter table table_name engine=InnoDB; to change the engine of the data table to support transactions.
*/
/**************** transaction--1 ***************/
$conn = mysql_connect('localhost','root' ,'root') or die ("Data connection error!!!");
mysql_select_db('test',$conn);
mysql_query("set names 'GBK'"); //Use GBK Chinese encoding;
//Start a Transaction
mysql_query("BEGIN"); //or mysql_query("START TRANSACTION");
$sql = "INSERT INTO `user` (`id`, `username`, `sex`) VALUES (NULL, '
$sql2 = "INSERT INTO `user` (`did`, `username`, `sex`) VALUES (NULL, 'test1', '0')";//I wrote this wrong on purpose
$res = mysql_query($ sql);
$res1 = mysql_query($sql2); 
if($res && $res1){
mysql_query("COMMIT");
echo 'Submitted successfully. ';
}else{
mysql_query("ROLLBACK");
echo 'Data rollback. ';
}
mysql_query("END"); 
/**************** transaction--2 ****************** /
/*Method 2*/
mysql_query("SET AUTOCOMMIT=0"); //Set mysql not to submit automatically, you need to submit it with a commit statement
$sql = "INSERT INTO `user` (`id`, `username`, ` sex`) VALUES (NULL, 'test1', '0')";
$sql2 = "INSERT INTO `user` (`did`, `username`, `sex`) VALUES (NULL, 'test1', '


if($res && $res1){
mysql_query("COMMIT");
echo 'Submitted successfully. ';
}else{
mysql_query("ROLLBACK");
echo 'Data rollback. ';
}
mysql_query("END"); //Don't forget mysql_query("SET AUTOCOMMIT=1") when the transaction is finished; auto commit


/******************For The MyISAM engine database that does not support transactions can use the method of table locking: ********************/


//MyISAM & InnoDB both support,
/*
LOCK TABLES can be locked with A table for the current thread. If the table is locked by other threads, block until all locks can be acquired.
UNLOCK TABLES can release any locks held by the current thread. All tables locked by the current thread are implicitly unlocked when the thread issues another LOCK TABLES, or when the connection to the server is closed.
*/

mysql_query("LOCK TABLES `user` WRITE");//Lock `user` table
$sql = "INSERT INTO `user` (`id`, `username`, `sex`) VALUES (NULL, 'test1 ', '0')";
$res = mysql_query($sql);
if($res){
echo 'Submitted successfully. !';
}else{
echo 'Failed!';
}
mysql_query("UNLOCK TABLES");//Unlock

MyISAM is the default storage engine in MySQL. Generally speaking, not many people care about this thing. Deciding what storage engine to use is a tricky thing, but it's worth looking into. This article only considers MyISAM and InnoDB, because these two are the most common.   

Let's answer some questions first:   
◆Does your database have foreign keys?   
◆Do you need transactional support?   
◆Do you need full-text indexing?   
◆ What query patterns do you often use?   
◆ How big is your data?   

myisam only has index cache   

innodb regardless of index file data file innodb buffer   

myisam can only manage indexes. When the index data is larger than the allocated resources, it will be cached by the operating system; data files depend on the cache of the operating system. Whether it is index or data, innodb manages and   

thinks the above problems by itself, so that you can find the right direction, but it is not absolute. If you need transactions or foreign keys, InnoDB might be the way to go. If you need a full text index, MyISAM is usually a good choice because it's built into the system, however, we don't actually test 2 million rows very often. So, even slower, we can get the full text index from InnoDB by using Sphinx.   

The size of the data is an important factor that affects what storage engine you choose. Large-sized data sets tend to choose the InnoDB method because it supports transaction processing and failure recovery. The size of the database determines the length of time for failure recovery. InnoDB can use transaction logs for data recovery, which will be faster. Whereas MyISAM can take hours or even days to do this, InnoDB only takes a few minutes.   

Your habits of manipulating database tables can also be a big factor in performance. For example: COUNT() will be very fast in MyISAM tables, but can be painful under InnoDB tables. The primary key query will be quite fast under InnoDB, but we need to be careful that if our primary key is too long, it will also cause performance problems. Bulk inserts are faster under MyISAM, but updates are faster under InnoDB - especially when there is a lot of concurrency.   

So, which one do you use? From experience, if it is some small application or project, then MyISAM may be more suitable. Of course, there are times when MyISAM is used with great success in large environments, but not always. If you are planning to use a very large data volume project and need transaction processing or foreign key support, then you should really go the InnoDB way directly. But keep in mind that InnoDB tables require more memory and storage, and converting a 100GB MyISAM table to an InnoDB table might give you a very bad experience.   

===================================================== =========   

MyISAM: This is the default type, it is based on the traditional ISAM type, ISAM is the abbreviation of Indexed Sequential Access Method (indexed sequential access method), it is the standard method for storing records and files .Compared with other storage engines, MyISAM has most of the tools to check and repair tables. MyISAM tables can be compressed, and they support full text search. They are not transaction-safe and do not support foreign keys. If the transaction is rolled back, it will cause an incomplete rollback, which is not atomic. MyISAM is a better choice if doing a lot of SELECTs.   

InnoDB: This type is transaction-safe. It has the same features as the BDB type, and they also support foreign keys. InnoDB tables are fast. Has richer features than BDB, so if you need a transaction-safe storage engine, it is recommended Use it. If your data performs a lot of INSERTs or UPDATEs, you should use InnoDB tables for performance reasons.   

For InnoDB type indexes that support transactions, the main reason for the speed is that AUTOCOMMIT is turned on by default, and the program There is no explicit call to BEGIN to start the transaction, resulting in automatic Commit every time one is inserted, which seriously affects the speed. You can call begin before executing sql, and multiple sqls form one thing (even if autocommit is turned on), which will greatly improve performance.   

===================================================== ============   

InnoDB and MyISAM are the two most commonly used table types in MySQL, each with their own advantages and disadvantages, depending on the specific application. The following are the known differences between the two, for reference only.   

innodb   
InnoDB provides MySQL with transaction-safe (ACID compliant) tables with commit, rollback, and crash recovery capabilities. InnoDB provides row locking (locking on row level), providing non-locking read in SELECTs consistent with the Oracle type. These features all improve the performance of multi-user concurrent operations. There is no need for lock escalation in InnoDB tables because InnoDB's row level locks are suitable for very small spaces. InnoDB is the first table engine on MySQL to provide FOREIGN KEY constraints.   

InnoDB is designed to handle high-volume database systems, and its CPU utilization is unmatched by other disk-based relational database engines. Technically, InnoDB is a complete database system behind MySQL. InnoDB builds its dedicated buffer pool in main memory for caching data and indexes. InnoDB stores data and indexes in tablespaces, which may contain multiple files, unlike others. For example, in MyISAM, tables are stored in separate files. The size of an InnoDB table is limited only by the file size of the operating system, which is typically 2 GB.   
All InnoDB tables are stored in the same data file ibdata1 (may be multiple files, or independent tablespace files), which is relatively difficult to backup. Free solutions can be to copy data files, backup binlog, Or use mysqldump.   


MyISAM   
MyISAM is the default storage engine for MySQL.   

Each MyISAM table is stored in three files. The frm file holds table definitions. The data file is MYD (MYData). The index file is an extension of MYI (MYIndex).   

Because MyISAM is relatively simple, it is better than InnoDB in efficiency. It is a good choice for small applications to use MyISAM.   

MyISAM tables are saved in the form of files. Using MyISAM storage in cross-platform data transfer will save a lot of trouble   

. There are some details and specific implementation differences:   

1. InnoDB does not support FULLTEXT type indexes.   
2. InnoDB does not save the specific number of rows in the table, that is to say, when executing select count(*) from table, InnoDB needs to scan the entire table to calculate how many rows there are, but MyISAM simply reads the number of saved rows That's it. Note that when the count(*) statement contains a where condition, the operations for both tables are the same.   
3. For fields of type AUTO_INCREMENT, InnoDB must contain an index of only this field, but in MyISAM tables, a joint index can be established with other fields.   
4. When DELETE FROM table, InnoDB will not recreate the table, but delete row by row.   
5. The LOAD TABLE FROM MASTER operation does not work for InnoDB. The solution is to first change the InnoDB table to a MyISAM table, import the data and then change it to an InnoDB table, but for additional InnoDB features (such as foreign keys) used Table does not apply.   

In addition, the row lock of the InnoDB table is not absolute. If MySQL cannot determine the range to be scanned when executing an SQL statement, the InnoDB table will also lock the entire table, such as update table set num=1 where name like “%aaa%”   

No kind of table is omnipotent. Only by selecting the appropriate table type for the business type can maximize the performance advantages of MySQL.   

===================================================== ============   


Here are some connections and differences between InnoDB and MyISAM!   

1. mysqld above 4.0 supports transactions, including non-max versions. 3.23 requires max version of mysqld to support transactions.   

2. If the type is not specified when creating a table, the default is myisam, which does not support transactions.   
The table type can be seen with the show create table tablename command.   

2.1 The start/commit operation on a table that does not support transactions has no effect. It has been submitted before commit is executed. Test:   
execute a msyql:   
use test;   
drop table if exists tn;   
create table tn (a varchar(10)) type= myisam;   
drop table if exists ty;   
create table ty (a varchar(10)) type=innodb;   

begin;   
insert into tn values('a');   
insert into ty values('a');   
select * from tn;   
select * from ty;   
You can see a record   

and execute another mysql:   
use test;   
select * from tn;   
select * from ty;   
only tn can see a record    and then commit   
on the other side    ; all records can be seen.   3. You can execute the following command to switch non-transactional table to transaction (data will not be lost), innodb table is safer than myisam table:       alter table tablename type=innodb;    3.1 innodb table cannot use the repair table command and myisamchk -r table_name    but can Use check table, and mysqlcheck [OPTIONS] database [tables]    ======================================= ==========================    MySQL using select for update must target InnoDb and be in a transaction to work.   The conditions of select are different, and whether row-level locks or table-level locks are used are also different.    Instructions for    going to http://www.neo.com.tw/archives/900
















Since InnoDB defaults to Row-Level Lock, MySQL will only execute Row Lock (lock only the selected data example) only if the primary key is "explicitly" specified, otherwise MySQL will execute Table Lock (lock the entire data table) live).   


For example:   

Suppose there is a form products, which has id and name two fields, id is the primary key.   

Example 1: (Specify the primary key, and have this data, row lock)   

SELECT * FROM products WHERE id='3' FOR UPDATE;   

Example 2: (Specify the primary key explicitly, if there is no such data, no lock)   

SELECT * FROM products WHERE id='-1' FOR UPDATE;   

Example 2: (No primary key, table lock)   

SELECT * FROM products WHERE name='Mouse' FOR UPDATE;   

Example 3: (Primary key ambiguous, table lock)   

SELECT * FROM products WHERE id<>'3' FOR UPDATE;   

Example 4: (Primary key is ambiguous, table lock)   

SELECT * FROM products WHERE id LIKE '3' FOR UPDATE;   

Note 1:   
FOR UPDATE is only applicable to InnoDB, and must be in the transaction block (BEGIN/COMMIT) to take effect

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324826235&siteId=291194637