<?php$servername = "localhost";$username = "username";$password = "password";try { $conn = new PDO("mysql:host=$servername", $username, $password); // 设置 PDO 错误模式为异常 $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); $sql = "CREATE DATABASE myDBPDO"; // 使用 exec() ,因为没有结果返回 $conn->exec($sql); echo "数据库创建成功<br>";}catch(PDOException $e){ echo $sql . "<br>" . $e->getMessage();}$conn = null;?>
<?php$servername = "localhost";$username = "username";$password = "password";$dbname = "myDBPDO";try { $conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password); // 设置 PDO 错误模式,用于抛出异常 $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); // 使用 sql 创建数据表 $sql = "CREATE TABLE MyGuests ( id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY, firstname VARCHAR(30) NOT NULL, lastname VARCHAR(30) NOT NULL, email VARCHAR(50), reg_date TIMESTAMP )"; // 使用 exec() ,没有结果返回 $conn->exec($sql); echo "数据表 MyGuests 创建成功";}catch(PDOException $e){ echo $sql . "<br>" . $e->getMessage();}$conn = null;?>
<?php$servername = "localhost";$username = "username";$password = "password";$dbname = "myDBPDO";try { $conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password); // set the PDO error mode to exception $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); // 开始事务 $conn->beginTransaction(); // SQL 语句 $conn->exec("INSERT INTO MyGuests (firstname, lastname, email) VALUES ('John', 'Doe', 'john@example.com')"); $conn->exec("INSERT INTO MyGuests (firstname, lastname, email) VALUES ('Mary', 'Moe', 'mary@example.com')"); $conn->exec("INSERT INTO MyGuests (firstname, lastname, email) VALUES ('Julie', 'Dooley', 'julie@example.com')"); // 提交事务 $conn->commit(); echo "新记录插入成功";}catch(PDOException $e){ // 如果执行失败回滚 $conn->rollback(); echo $sql . "<br>" . $e->getMessage();}$conn = null;?>