[英]MySQL - PHP Transactions and table locks
I am using $db->begin_transaction(MYSQLI_TRANS_START_READ_WRITE);
我正在使用$db->begin_transaction(MYSQLI_TRANS_START_READ_WRITE);
to begin a transaction. 开始交易。 Will this lock the tables involving in the transactions? 这会锁定涉及交易的表吗?
If Yes, what happens when simultaneous users are involved (multiple transactions at the same time). 如果是,则涉及同时用户(同时进行多个事务)时会发生什么。
PS: I don't want to lock any table. PS:我不想锁定任何桌子。
When you write in table, the table always will be locked. 当您在表中写入数据时,该表将始终被锁定。 This is to save database. 这是为了保存数据库。
The transaction is a complete process of save o update data in your database. 事务是在数据库中保存或更新数据的完整过程。 This is used to maintain the integrity and relation of the data. 这用于维护数据的完整性和关系。
For example: if a one query fail, the process maybe discard with "rollback" and go back to initial status. 例如:如果一个查询失败,则该过程可能会通过“回滚”放弃并返回到初始状态。 if process finished with success persist data with "commit". 如果过程成功完成,则用“ commit”保留数据。
Code example: 代码示例:
try
{
// Disable auto commit
mysqli_autocommit( $db_conn, FALSE );
$query = "TRUNCATE TABLE `table`;";
if( ! mysqli_query( $db_conn, $query ) )
{
throw new \Exception( "ERROR TRUNCATE: ".$query, 1 );
}
foreach( $data as $d )
{
$query = "INSERT INTO ....";
if( ! mysqli_query( $db_conn, $query ) )
{
throw new \Exception( "ERROR INSERT: ".$query, 2 );
}
}
// Success finish
mysqli_commit( $db_conn );
}
catch( \Exception $e )
{
echo $e->getMessage()."\n";
echo "errno: " . mysqli_errno( $db_conn ) . PHP_EOL . "\n";
echo "error: " . mysqli_error( $db_conn ) . PHP_EOL . "\n";
// Go back to initial status
mysqli_rollback( $db_conn );
}
Nothing of that kind happens on BEGIN TRANSACTION
. 在BEGIN TRANSACTION
上什么也没有发生。 It just means: "start recording of what I like to do". 它只是意味着:“开始记录我喜欢做的事情”。
All this is then executed when you do the COMMIT
or just discarded if you ROLLBACK
. 然后,在执行COMMIT
时将执行所有这些操作;如果您执行ROLLBACK
则将其丢弃。
If you have data changing queries in that transaction like INSERT
, UPDATE
or DELETE
, the table locks will be issued as normal during the commit. 如果您在该事务中有数据更改查询(例如INSERT
, UPDATE
或DELETE
,则在提交期间将正常发出表锁。 On begin, the engine doesn't even know what you are going to do next, so it actually could not lock anything at that point. 开始时,引擎甚至不知道接下来要做什么,因此它实际上无法锁定任何内容。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.