如何寫一個屬於自己的資料庫封裝(2)
Connector.php
負責與資料庫通信,增刪改讀(CRUD)
首先, 建立一個Connector類, 且設定屬性
<?php class Connector { // 数据库地址前缀,常见的有mysql,slqlsrv,odbc等等等 private $driver = 'mysql'; // 数据库地址 private $host = 'localhost'; // 数据库默认名称, 设置为静态是因为有切换数据库的需求 private static $db = 'sakila'; // 数据库用户名 private $username = 'root'; // 数据库密码 private $password = ''; // 当前数据库连接 protected $connection; // 数据库连接箱,切换已存在的数据库连接不需要重新通信,从这里取即可 protected static $container = []; // PDO默认属性配置,具体请自行查看文档 protected $options = [ PDO::ATTR_CASE => PDO::CASE_NATURAL, PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION, PDO::ATTR_ORACLE_NULLS => PDO::NULL_NATURAL, PDO::ATTR_STRINGIFY_FETCHES => false, ]; }
以上程式碼配合註解應該可以理解了所以不多解釋了,直接進入函數
-
buildConnectString - 就是產生DSN連接串,非常直白
protected function buildConnectString() { return "$this->driver:host=$this->host;dbname=".self::$db; } // "mysql:host=localhost;dbname=sakila;"
登入後複製 -
connect - 連接資料庫
public function connect() { try { // 连接数据库,生成pdo实例, 将之赋予$connection,并存入$container之中 self::$container[self::$db] = $this->connection = new PDO($this->buildConnectString(), $this->username, $this->password, $this->options); // 返回数据库连接 return $this->connection; } catch (Exception $e) { // 若是失败, 返回原因 // 还记得dd()吗?这个辅助函数还会一直用上 dd($e->getMessage()); } }
登入後複製 -
setDatabase - 切換資料庫
public function setDatabase($db) { self::$db = $db; return $this; }
登入後複製 -
_construct - 產生實例後第一步要幹嘛
function construct() { // 如果从未连接过该数据库, 那就新建连接 if(empty(self::$container[self::$db])) $this->connect(); // 反之, 从$container中提取, 无需再次通信 $this->connection = self::$container[self::$db]; }
登入後複製
接下來兩個函數式配合著用的,單看可能會懵逼, 配合範例單步調試
$a = new Connector(); $bindValues = [ 'PENELOPE', 'GUINESS' ]; dd($a->read('select * from actor where first_name = ? and last_name = ?', $bindValues));
傳回值
array (size=1) 0 => object(stdClass)[4] public 'actor_id' => string '1' (length=1) public 'first_name' => string 'PENELOPE' (length=8) public 'last_name' => string 'GUINESS' (length=7) public 'last_update' => string '2006-02-15 04:34:33' (length=19)
-
read - 讀取資料
public function read($sql, $bindings) { // 将sql语句放入预处理函数 // $sql = select * from actor where first_name = ? and last_name = ? $statement = $this->connection->prepare($sql); // 将附带参数带入pdo实例 // $bindings = ['PENELOPE', 'GUINESS'] $this->bindValues($statement, $bindings); // 执行 $statement->execute(); // 返回所有合法数据, 以Object对象为数据类型 return $statement->fetchAll(PDO::FETCH_OBJ); }
登入後複製 -
bindValues - 將附帶參數帶入pdo實例
// 从例子中可以看出, 我用在预处理的变量为?, 这是因为pdo的局限性, 有兴趣可以在评论区讨论这个问题 public function bindValues($statement, $bindings) { // $bindings = ['PENELOPE', 'GUINESS'] // 依次循环每一个参数 foreach ($bindings as $key => $value) { // $key = 0/1 // $value = 'PENELOPE'/'GUINESS' $statement->bindValue( // 如果是字符串类型, 那就直接使用, 反之是数字, 将其+1 // 这里是数值, 因此返回1/2 is_string($key) ? $key : $key + 1, // 直接放入值 // 'PENELOPE'/'GUINESS' $value, // 这里直白不多说 // PDO::PARAM_STR/PDO::PARAM_STR is_int($value) ? PDO::PARAM_INT : PDO::PARAM_STR ); } }
登入後複製所以懂了嗎 _( :3”∠)
-
update - 改寫資料
// 与read不同的地方在于, read返回数据, update返回boolean(true/false) public function update($sql, $bindings) { $statement = $this->connection->prepare($sql); $this->bindValues($statement, $bindings); return $statement->execute(); }
登入後複製 -
// 与update一样, 分开是因为方便日后维护制定 public function delete($sql, $bindings) { $statement = $this->connection->prepare($sql); $this->bindValues($statement, $bindings); return $statement->execute(); }
登入後複製 -
create - 增加資料
// 返回最新的自增ID, 如果有 public function create($sql, $bindings) { $statement = $this->connection->prepare($sql); $this->bindValues($statement, $bindings); $statement->execute(); return $this->lastInsertId(); }
登入後複製 -
lastInsertId - 傳回新增id, 如果有
// pdo自带,只是稍微封装 public function lastInsertId() { $id = $this->connection->lastInsertId(); return empty($id) ? null : $id; }
登入後複製
過於進階複雜的SQL語句可能無法封裝, 因此準備了可直接用RAW query通訊資料庫的兩個函數
-
exec - 適用於增刪改
public function exec($sql) { return $this->connection->exec($sql); }
登入後複製 -
query - 適用於讀取
public function query($sql) { $q = $this->connection->query($sql); return $q->fetchAll(PDO::FETCH_OBJ); }
登入後複製
將資料庫事務相關的函數封裝起來, 直白所以沒有註釋
public function beginTransaction() { $this->connection->beginTransaction(); return $this; } public function rollBack() { $this->connection->rollBack(); return $this; } public function commit() { $this->connection->commit(); return $this; } public function inTransaction() { return $this->connection->inTransaction(); }
完整程式碼
<?php class Connector { // 数据库地址前缀,常见的有mysql,slqlsrv,odbc等等等 private $driver = 'mysql'; // 数据库地址 private $host = 'localhost'; // 数据库默认名称, 设置为静态是因为有切换数据库的需求 private static $db = 'sakila'; // 数据库用户名 private $username = 'root'; // 数据库密码 private $password = ''; // 当前数据库连接 protected $connection; // 数据库连接箱,切换已存在的数据库连接不需要重新通信,从这里取即可 protected static $container = []; // PDO默认属性配置,具体请自行查看文档 protected $options = [ PDO::ATTR_CASE => PDO::CASE_NATURAL, PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION, PDO::ATTR_ORACLE_NULLS => PDO::NULL_NATURAL, PDO::ATTR_STRINGIFY_FETCHES => false, ]; function construct() { // 如果从未连接过该数据库, 那就新建连接 if(empty(self::$container[self::$db])) $this->connect(); // 反之, 从$container中提取, 无需再次通信 $this->connection = self::$container[self::$db]; } // 生成DSN连接串 protected function buildConnectString() { return "$this->driver:host=$this->host;dbname=".self::$db; } // 连接数据库 public function connect() { try { // 连接数据库,生成pdo实例, 将之赋予$connection,并存入$container之中 self::$container[self::$db] = $this->connection = new PDO($this->buildConnectString(), $this->username, $this->password, $this->options); // 返回数据库连接 return $this->connection; } catch (Exception $e) { // 若是失败, 返回原因 dd($e->getMessage()); } } // 切换数据库 public function setDatabase($db) { self::$db = $db; return $this; } // 读取数据 public function read($sql, $bindings) { // 将sql语句放入预处理函数 $statement = $this->connection->prepare($sql); // 将附带参数带入pdo实例 $this->bindValues($statement, $bindings); // 执行 $statement->execute(); // 返回所有合法数据, 以Object对象为数据类型 return $statement->fetchAll(PDO::FETCH_OBJ); } // 将附带参数带入pdo实例 public function bindValues($statement, $bindings) { // 依次循环每一个参数 foreach ($bindings as $key => $value) { $statement->bindValue( // 如果是字符串类型, 那就直接使用, 反之是数字, 将其+1 is_string($key) ? $key : $key + 1, // 直接放入值 $value, // 这里直白不多说 is_int($value) ? PDO::PARAM_INT : PDO::PARAM_STR ); } } // 改写数据 public function update($sql, $bindings) { // 与read不同的地方在于, read返回数据, update返回boolean(true/false) $statement = $this->connection->prepare($sql); $this->bindValues($statement, $bindings); return $statement->execute(); } // 删除数据 public function delete($sql, $bindings) { $statement = $this->connection->prepare($sql); $this->bindValues($statement, $bindings); return $statement->execute(); } // 增加数据 public function create($sql, $bindings) { $statement = $this->connection->prepare($sql); $this->bindValues($statement, $bindings); $statement->execute(); return $this->lastInsertId(); } // 返回新增id, 如果有 public function lastInsertId() { $id = $this->connection->lastInsertId(); return empty($id) ? null : $id; } // 适用于增删改 public function exec($sql) { return $this->connection->exec($sql); } // 适用于读 public function query($sql) { $q = $this->connection->query($sql); return $q->fetchAll(PDO::FETCH_OBJ); } public function beginTransaction() { $this->connection->beginTransaction(); return $this; } public function rollBack() { $this->connection->rollBack(); return $this; } public function commit() { $this->connection->commit(); return $this; } public function inTransaction() { return $this->connection->inTransaction(); } }
本期疑問
1.) 因為php本身的特性, 預設運行完所有程式碼類別會自行析構,pdo自動斷聯, 所以我沒有disconnect(),讓pdo斷開連接, 不知這樣是不是一種bad practice?
2.) 增加和改寫數據的兩個函數並不支持多組數據一次性加入,只能單次增該, 原因是我之前寫了嫌太繁瑣所以刪了, 有心的童鞋可以提供方案
以上是如何寫一個屬於自己的資料庫封裝(2)的詳細內容。更多資訊請關注PHP中文網其他相關文章!

熱AI工具

Undresser.AI Undress
人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover
用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool
免費脫衣圖片

Clothoff.io
AI脫衣器

Video Face Swap
使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱門文章

熱工具

記事本++7.3.1
好用且免費的程式碼編輯器

SublimeText3漢化版
中文版,非常好用

禪工作室 13.0.1
強大的PHP整合開發環境

Dreamweaver CS6
視覺化網頁開發工具

SublimeText3 Mac版
神級程式碼編輯軟體(SublimeText3)

全表掃描在MySQL中可能比使用索引更快,具體情況包括:1)數據量較小時;2)查詢返回大量數據時;3)索引列不具備高選擇性時;4)複雜查詢時。通過分析查詢計劃、優化索引、避免過度索引和定期維護表,可以在實際應用中做出最優選擇。

是的,可以在 Windows 7 上安裝 MySQL,雖然微軟已停止支持 Windows 7,但 MySQL 仍兼容它。不過,安裝過程中需要注意以下幾點:下載適用於 Windows 的 MySQL 安裝程序。選擇合適的 MySQL 版本(社區版或企業版)。安裝過程中選擇適當的安裝目錄和字符集。設置 root 用戶密碼,並妥善保管。連接數據庫進行測試。注意 Windows 7 上的兼容性問題和安全性問題,建議升級到受支持的操作系統。

InnoDB的全文搜索功能非常强大,能够显著提高数据库查询效率和处理大量文本数据的能力。1)InnoDB通过倒排索引实现全文搜索,支持基本和高级搜索查询。2)使用MATCH和AGAINST关键字进行搜索,支持布尔模式和短语搜索。3)优化方法包括使用分词技术、定期重建索引和调整缓存大小,以提升性能和准确性。

聚集索引和非聚集索引的區別在於:1.聚集索引將數據行存儲在索引結構中,適合按主鍵查詢和範圍查詢。 2.非聚集索引存儲索引鍵值和數據行的指針,適用於非主鍵列查詢。

MySQL是一個開源的關係型數據庫管理系統。 1)創建數據庫和表:使用CREATEDATABASE和CREATETABLE命令。 2)基本操作:INSERT、UPDATE、DELETE和SELECT。 3)高級操作:JOIN、子查詢和事務處理。 4)調試技巧:檢查語法、數據類型和權限。 5)優化建議:使用索引、避免SELECT*和使用事務。

MySQL 數據庫中,用戶和數據庫的關係通過權限和表定義。用戶擁有用戶名和密碼,用於訪問數據庫。權限通過 GRANT 命令授予,而表由 CREATE TABLE 命令創建。要建立用戶和數據庫之間的關係,需創建數據庫、創建用戶,然後授予權限。

MySQL 和 MariaDB 可以共存,但需要謹慎配置。關鍵在於為每個數據庫分配不同的端口號和數據目錄,並調整內存分配和緩存大小等參數。連接池、應用程序配置和版本差異也需要考慮,需要仔細測試和規劃以避免陷阱。在資源有限的情況下,同時運行兩個數據庫可能會導致性能問題。

MySQL支持四種索引類型:B-Tree、Hash、Full-text和Spatial。 1.B-Tree索引適用於等值查找、範圍查詢和排序。 2.Hash索引適用於等值查找,但不支持範圍查詢和排序。 3.Full-text索引用於全文搜索,適合處理大量文本數據。 4.Spatial索引用於地理空間數據查詢,適用於GIS應用。
