php addBatch
时间: 2023-10-03 08:02:45 浏览: 61
addBatch is a method in the PHP PDO class that allows you to execute multiple SQL statements in a single call to the database.
Here's an example:
```
// Create a PDO object and connect to the database
$db = new PDO('mysql:host=localhost;dbname=mydb', 'username', 'password');
// Start a transaction
$db->beginTransaction();
// Prepare the SQL statements
$sql1 = "UPDATE users SET name = 'John' WHERE id = 1";
$sql2 = "UPDATE users SET name = 'Jane' WHERE id = 2";
// Add the SQL statements to the batch
$db->prepare($sql1)->execute();
$db->prepare($sql2)->execute();
// Commit the transaction
$db->commit();
```
In this example, we first create a PDO object and connect to the database. We then start a transaction using the `beginTransaction()` method.
Next, we prepare two SQL statements using the `prepare()` method and store them in the `$sql1` and `$sql2` variables.
We then add these SQL statements to the batch using the `execute()` method. Finally, we commit the transaction using the `commit()` method.
The `addBatch()` method is not used in this example because we are using the `execute()` method to add the SQL statements to the batch. However, you can use the `addBatch()` method to add SQL statements to the batch as well. The difference is that `execute()` immediately executes the SQL statement, while `addBatch()` adds it to the batch to be executed later.
Here's an example of using `addBatch()`:
```
// Prepare the SQL statements
$sql1 = "UPDATE users SET name = 'John' WHERE id = 1";
$sql2 = "UPDATE users SET name = 'Jane' WHERE id = 2";
// Create a PDO object and connect to the database
$db = new PDO('mysql:host=localhost;dbname=mydb', 'username', 'password');
// Start a transaction
$db->beginTransaction();
// Add the SQL statements to the batch
$db->prepare($sql1)->addBatch();
$db->prepare($sql2)->addBatch();
// Execute the batch
$db->executeBatch();
// Commit the transaction
$db->commit();
```
In this example, we first prepare the SQL statements as before.
We then create a PDO object and connect to the database.
Next, we start a transaction using `beginTransaction()`.
Instead of using `execute()` to add the SQL statements to the batch, we use `addBatch()` to add them.
After adding the SQL statements to the batch, we execute the batch using the `executeBatch()` method.
Finally, we commit the transaction using the `commit()` method.
阅读全文