php的pdo->exec,pdo操作数据库的方法——exec()

本文详细介绍了PHP中PDO对象的exec()方法使用方法,包括创建数据表、执行插入、更新、删除操作以及获取最后插入ID等场景。通过具体实例展示了如何利用exec()方法高效地操作数据库。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

favicon.ico摘要:exec():执行一条sql语句,并返回其受影响的记录,如果没有受影响的记录则返回0。【注意:exec()对select查询语句没有作用】

1、exec创建数据表<?php

try{

$pdo=new PDO('mysql:host=localhost;dbname=test','root','root');

$sql=<<

CREATE TABLE IF NOT EXISTS test_pdo(

id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,

username CHAR(16) NOT NULL UNIQUE,

password CHAR(32) NOT NULL,

email VARCHAR(32) NOT NULL

);

EOF;

$res=$pdo->exec($sql);

var_dump($res);

}catch(PDOException $e){

echo $e->getMessage();

}

20190325_1553506568684452.jpg

2、exec执行插入insert语句<?php

try{

$pdo=new PDO('mysql:host=localhost;dbname=test','root','root');

$sql='INSERT test_pdo(username,password,email)

VALUES

("testuser","'.md5('123456').'","testuser@qq.com")';

$res=$pdo->exec($sql);

echo $res;

}catch(PDOException $e){

echo $e->getMessage();

}

20190325_1553506748191611.jpg

3、exec执行多条数据插入

try{

$pdo=new PDO('mysql:host=localhost;dbname=test','root','root');

$sql='INSERT test_pdo(username,password,email)

VALUES

("testuser1","'.md5('123456').'","testuser1@qq.com"),

("testuser2","'.md5('123456').'","testuser2@qq.com"),

("testuser3","'.md5('123456').'","testuser3@qq.com")';

$res=$pdo->exec($sql);

echo '受影响的记录的条数为:'.$res;

}catch(PDOException $e){

echo $e->getMessage();

}

20190325_1553507310707246.jpg

4、exec获取最后插入数据的ID号<?php

try{

$pdo=new PDO('mysql:host=localhost;dbname=test','root','root');

$sql='INSERT test_pdo(username,password,email)

VALUES

("testuser4","'.md5('123456').'","testuser4@qq.com")';

$res=$pdo->exec($sql);

echo '受影响的记录的条数为:'.$res.'
';

echo '最后插入的ID号为'.$pdo->lastInsertId();

}catch(PDOException $e){

echo $e->getMessage();

}

20190325_1553507544135519.jpg

5、exec执行update语句<?php

try{

$pdo=new PDO('mysql:host=localhost;dbname=test','root','root');

$sql='update test_pdo set username="update_name" where id=1';

$res=$pdo->exec($sql);

echo '受影响的记录的条数为:'.$res;

}catch(PDOException $e){

echo $e->getMessage();

}

20190325_1553507796538079.jpg

6、exec执行delete语句<?php

try{

$pdo=new PDO('mysql:host=localhost;dbname=test','root','root');

$sql='delete from test_pdo where id=1';

$res=$pdo->exec($sql);

echo '受影响的记录的条数为:'.$res;

}catch(PDOException $e){

echo $e->getMessage();

}

20190325_1553507900547843.jpg

<?php /** * SQLite数据库操作类库 * 功能:连接管理、CRUD操作、事务支持、预处理语句 */ class SQLiteDB { private $db_path; private $pdo; private $error; /** * 构造函数 - 创建数据库连接 * @param string $db_path 数据库文件路径 */ public function __construct($db_path) { $this->db_path = $db_path; try { // 创建PDO连接(SQLite是文件型数据库) $this->pdo = new PDO("sqlite:" . $this->db_path); // 设置错误模式为异常 $this->pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); // 启用外键支持 $this->pdo->exec("PRAGMA foreign_keys = ON"); } catch (PDOException $e) { $this->error = $e->getMessage(); throw new Exception("数据库连接失败: " . $this->error); } } // private static function instance() // { // if (!self::$db) { // self::$db = new SQLiteDB(); // } // } public function prepare($sql) { return $this->pdo->prepare($sql); } public function prepareAndExecute($sql, $data = []) { if (!empty($data)) { // 参数绑定和执行 $stmt = $this->pdo->prepare($sql); foreach ($data as $key => &$value) { switch (gettype($value)) { case 'integer': $stmt->bindValue(":" . $key, $value, PDO::PARAM_INT); break; case 'double': $stmt->bindValue(":" . $key, $value, PDO::PARAM_STR); break; default: $stmt->bindValue(":" . $key, $value, PDO::PARAM_STR); } } return $stmt->execute(); } else { // 直接执行 SQL 查询 return $this->pdo->exec($sql); } } /** * 执行查询语句(返回结果集) * @param string $sql SQL语句(支持预处理占位符) * @param array $params 绑定参数数组 * @return PDOStatement 结果集对象 */ // public function query($sql, $params = []) { // try { // $stmt = $this->pdo->prepare($sql); // $stmt->execute($params); // return $stmt; // } catch (PDOException $e) { // throw new Exception("查询执行失败: " . $e->getMessage()); // } // } /** * 执行更新操作(增删改) * @param string $sql SQL语句 * @param array $params 绑定参数数组 * @return int 受影响的行数 */ public function execute($sql, $params = []) { try { $stmt = $this->pdo->prepare($sql); $stmt->execute($params); return $stmt->rowCount(); } catch (PDOException $e) { throw new Exception("操作执行失败: " . $e->getMessage()); } } /** * 查询单个字段 * @param string $sql * @return void|string */ // public static function querySingle($sql) // { // self::instance(); // $result = @self::$db->querySingle($sql); // return $result ? $result : ''; // } /** * 获取单行数据获取一行结果 * @param string $sql SQL语句 * @param array $params 绑定参数数组 * @return array 单行数据数组 */ // public function fetchRow($sql, $params = []) { // self::instance(); // $result = @self::$db->querySingle($sql, true); // return $result; // } public function fetchRow($sql) { // 获取一行结果 $stmt = $this->pdo->query($sql); if ($row = $stmt->fetch(PDO::FETCH_ASSOC)) { return $row; } return null; } /** * 获取全部数据 * @param string $sql SQL语句 * @param array $params 绑定参数数组 * @return array 二维数据数组 */ public function fetchAll($sql) { $stmt = $this->pdo->query($sql); return $stmt->fetchAll(PDO::FETCH_ASSOC); } /** * 获取最后插入的ID * @return string 最后插入行的ID */ public function lastInsertId() { return $this->pdo->lastInsertId(); } /** * 开启事务 */ public function beginTransaction() { $this->pdo->beginTransaction(); } /** * 提交事务 */ public function commit() { $this->pdo->commit(); } /** * 回滚事务 */ public function rollBack() { $this->pdo->rollBack(); } 完善操作sqlite数据库的类库
最新发布
07-15
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值