PHP的Yii架構中使用資料庫的配置和SQL操作執行個體教程_php執行個體

來源:互聯網
上載者:User

資料庫訪問 (DAO)
Yii 包含了一個建立在 PHP PDO 之上的資料訪問層 (DAO). DAO為不同的資料庫提供了一套統一的API. 其中ActiveRecord 提供了資料庫與模型(MVC 中的 M,Model) 的互動,QueryBuilder 用於建立動態查詢語句. DAO提供了簡單高效的SQL查詢,可以用在與資料庫互動的各個地方.

Yii 預設支援以下資料庫 (DBMS):

  • MySQL
  • MariaDB
  • SQLite
  • PostgreSQL
  • CUBRID: 版本 >= 9.3 . (由於PHP PDO 擴充的一個bug 引用值會無效,所以你需要在 CUBRID的用戶端和服務端都使用 9.3 )
  • Oracle
  • MSSQL: 版本>=2005.

配置

開始使用資料庫首先需要設定資料庫串連組件,通過添加 db 組件到應用配置實現("基礎的" Web 應用程式是 config/web.php),DSN( Data Source Name )是資料來源名稱,用於指定資料庫資訊.如下所示:

return [  // ...  'components' => [    // ...    'db' => [      'class' => 'yii\db\Connection',      'dsn' => 'mysql:host=localhost;dbname=mydatabase', // MySQL, MariaDB      //'dsn' => 'sqlite:/path/to/database/file', // SQLite      //'dsn' => 'pgsql:host=localhost;port=5432;dbname=mydatabase', // PostgreSQL      //'dsn' => 'cubrid:dbname=demodb;host=localhost;port=33000', // CUBRID      //'dsn' => 'sqlsrv:Server=localhost;Database=mydatabase', // MS SQL Server, sqlsrv driver      //'dsn' => 'dblib:host=localhost;dbname=mydatabase', // MS SQL Server, dblib driver      //'dsn' => 'mssql:host=localhost;dbname=mydatabase', // MS SQL Server, mssql driver      //'dsn' => 'oci:dbname=//localhost:1521/mydatabase', // Oracle      'username' => 'root', //資料庫使用者名稱      'password' => '', //資料庫密碼      'charset' => 'utf8',    ],  ],  // ...];

請參考PHP manual擷取更多有關 DSN 格式資訊。 配置串連組件後可以使用以下文法訪問:

$connection = \Yii::$app->db;

請參考yii\db\Connection擷取可配置的屬性列表。 如果你想通過ODBC串連資料庫,則需要配置yii\db\Connection::driverName 屬性,例如:

'db' => [  'class' => 'yii\db\Connection',  'driverName' => 'mysql',  'dsn' => 'odbc:Driver={MySQL};Server=localhost;Database=test',  'username' => 'root',  'password' => '',],

注意:如果需要同時使用多個資料庫可以定義 多個 串連組件:

return [  // ...  'components' => [    // ...    'db' => [      'class' => 'yii\db\Connection',      'dsn' => 'mysql:host=localhost;dbname=mydatabase',       'username' => 'root',      'password' => '',      'charset' => 'utf8',    ],    'secondDb' => [      'class' => 'yii\db\Connection',      'dsn' => 'sqlite:/path/to/database/file',     ],  ],  // ...];

在代碼中通過以下方式使用:

$primaryConnection = \Yii::$app->db;$secondaryConnection = \Yii::$app->secondDb;

如果不想定義資料庫連接為全域應用組件,可以在代碼中直接初始化使用:

$connection = new \yii\db\Connection([  'dsn' => $dsn,   'username' => $username,   'password' => $password,]);$connection->open();

小提示:如果在建立了串連後需要執行額外的 SQL 查詢,可以添加以下代碼到應用設定檔:

return [  // ...  'components' => [    // ...    'db' => [      'class' => 'yii\db\Connection',      // ...      'on afterOpen' => function($event) {        $event->sender->createCommand("SET time_zone = 'UTC'")->execute();      }    ],  ],  // ...];

如果執行 SQL 不返回任何資料可使用命令中的 execute 方法:

$command = $connection->createCommand('UPDATE post SET status=1 WHERE id=1');$command->execute();

你可以使用insert,update,delete 方法,這些方法會根據參數產生合適的SQL並執行.

// INSERT$connection->createCommand()->insert('user', [  'name' => 'Sam',  'age' => 30,])->execute();// INSERT 一次插入多行$connection->createCommand()->batchInsert('user', ['name', 'age'], [  ['Tom', 30],  ['Jane', 20],  ['Linda', 25],])->execute();// UPDATE$connection->createCommand()->update('user', ['status' => 1], 'age > 30')->execute();// DELETE$connection->createCommand()->delete('user', 'status = 0')->execute();

引用的表名和列名

大多數時間都使用以下文法來安全地參考資料表名和列名:

$sql = "SELECT COUNT($column) FROM {{table}}";$rowCount = $connection->createCommand($sql)->queryScalar();

以上代碼$column 會轉變為引用恰當的列名,而{{table}} 就轉變為引用恰當的表名。 表名有個特殊的變數 {{%Y}} ,如果設定了表首碼使用該變體可以自動在表名前添加首碼:

$sql = "SELECT COUNT($column) FROM {{%$table}}";$rowCount = $connection->createCommand($sql)->queryScalar();

如果在設定檔如下設定了表首碼,以上代碼將在 tbl_table 這個表查詢結果:

return [  // ...  'components' => [    // ...    'db' => [      // ...      'tablePrefix' => 'tbl_',    ],  ],];

手工參考資料表名和列名的另一個選擇是使用yii\db\Connection::quoteTableName() 和 yii\db\Connection::quoteColumnName():

$column = $connection->quoteColumnName($column);$table = $connection->quoteTableName($table);$sql = "SELECT COUNT($column) FROM $table";$rowCount = $connection->createCommand($sql)->queryScalar();

預先處理語句

為安全傳遞查詢參數可以使用預先處理語句,首先應當使用:placeholder佔位,再將變數綁定到對應預留位置:

$command = $connection->createCommand('SELECT * FROM post WHERE id=:id');$command->bindValue(':id', $_GET['id']);$post = $command->query();

另一種用法是準備一次預先處理語句而執行多次查詢:

$command = $connection->createCommand('DELETE FROM post WHERE id=:id');$command->bindParam(':id', $id);$id = 1;$command->execute();$id = 2;$command->execute();

提示,在執行前綁定變數,然後在每個執行中改變變數的值(一般用在迴圈中)比較高效.
事務

當你需要順序執行多個相關的的query時,你可以把他們封裝到一個事務中去保護資料一致性.Yii提供了一個簡單的介面來實現事務操作. 如下執行 SQL 事務查詢語句:

$transaction = $connection->beginTransaction();try {  $connection->createCommand($sql1)->execute();   $connection->createCommand($sql2)->execute();  // ... 執行其他 SQL 陳述式 ...  $transaction->commit();} catch(Exception $e) {  $transaction->rollBack();}

我們通過yii\db\Connection::beginTransaction()開始一個事務,通過try catch 捕獲異常.當執行成功,通過yii\db\Transaction::commit()提交事務並結束,當發生異常失敗通過yii\db\Transaction::rollBack()進行交易回復.

如需要也可以嵌套多個事務:

// 外部事務$transaction1 = $connection->beginTransaction();try {  $connection->createCommand($sql1)->execute();  // 內部事務  $transaction2 = $connection->beginTransaction();  try {    $connection->createCommand($sql2)->execute();    $transaction2->commit();  } catch (Exception $e) {    $transaction2->rollBack();  }  $transaction1->commit();} catch (Exception $e) {  $transaction1->rollBack();}

注意你使用的資料庫必須支援Savepoints才能正確地執行,以上代碼在所有關係資料中都可以執行,但是只有支援Savepoints才能保證安全性。
Yii 也支援為事務設定隔離等級isolation levels,當執行事務時會使用資料庫預設的隔離等級,你也可以為事物指定隔離等級. Yii 提供了以下常量作為常用的隔離等級

  • \yii\db\Transaction::READ_UNCOMMITTED - 允許讀取改變了的還未提交的資料,可能導致髒讀、不可重複讀取和幻讀
  • \yii\db\Transaction::READ_COMMITTED - 允許並發事務提交之後讀取,可以避免髒讀,可能導致重複讀和幻讀。
  • \yii\db\Transaction::REPEATABLE_READ - 對相同欄位的多次讀取結果一致,可導致幻讀。
  • \yii\db\Transaction::SERIALIZABLE - 完全服從ACID的原則,確保不發生髒讀、不可重複讀取和幻讀。

你可以使用以上常量或者使用一個string字串命令,在對應資料庫中執行該命令用以設定隔離等級,比如對於postgres有效命令為SERIALIZABLE READ ONLY DEFERRABLE.

注意:某些資料庫只能針對串連來設定交易隔離等級,所以你必須要為串連明確制定隔離等級.目前受影響的資料庫:MSSQL SQLite

注意:SQLite 只支援兩種交易隔離等級,所以你只能設定READ UNCOMMITTED 和 SERIALIZABLE.使用其他隔離等級會拋出異常.

注意:PostgreSQL 不允許在事務開始前設定隔離等級,所以你不能在事務開始時指定隔離等級.你可以在事務開始之後調用yii\db\Transaction::setIsolationLevel() 來設定.
關於隔離等級[isolation levels]: http://en.wikipedia.org/wiki/Isolation_(database_systems)#Isolation_levels

資料庫複寫和讀寫分離

很多資料庫支援資料庫複寫 http://en.wikipedia.org/wiki/Replication_(computing)#Database_replication">database replication來提高可用性和響應速度. 在資料庫複寫中,資料總是從主伺服器 到 從伺服器. 所有的插入和更新等寫操作在主伺服器執行,而讀操作在從伺服器執行.

通過配置yii\db\Connection可以實現資料庫複寫和讀寫分離.

[  'class' => 'yii\db\Connection',  // 配置主伺服器  'dsn' => 'dsn for master server',  'username' => 'master',  'password' => '',  // 配置從伺服器  'slaveConfig' => [    'username' => 'slave',    'password' => '',    'attributes' => [      // use a smaller connection timeout      PDO::ATTR_TIMEOUT => 10,    ],  ],  // 配置從伺服器組  'slaves' => [    ['dsn' => 'dsn for slave server 1'],    ['dsn' => 'dsn for slave server 2'],    ['dsn' => 'dsn for slave server 3'],    ['dsn' => 'dsn for slave server 4'],  ],]

以上的配置實現了一主多從的結構,從伺服器用以執行讀查詢,主伺服器執行寫入查詢,讀寫分離的功能由後台代碼自動完成.調用者無須關心.例如:

// 使用以上配置建立資料庫連接對象$db = Yii::createObject($config);// 通過從伺服器執行查詢操作$rows = $db->createCommand('SELECT * FROM user LIMIT 10')->queryAll();// 通過主伺服器執行更新操作$db->createCommand("UPDATE user SET username='demo' WHERE id=1")->execute();

注意:通過yii\db\Command::execute() 執行的查詢被認為是寫操作,所有使用yii\db\Command來執行的其他查詢方法被認為是讀操作.你可以通過$db->slave得到當前正在使用能夠的從伺服器.
Connection組件支援從伺服器的負載平衡和容錯移轉,當第一次執行讀查詢時,會隨即選擇一個從伺服器進行串連,如果串連失敗則又選擇另一個,如果所有從伺服器都不可用,則會串連主伺服器。你可以配置yii\db\Connection::serverStatusCache來記住那些不能串連的從伺服器,使Yii 在一段時間[[yii\db\Connection::serverRetryInterval].內不會重複嘗試串連那些根本停用從伺服器.

注意:在上述配置中,每個從伺服器連線逾時時間被指定為10s. 如果在10s內不能串連,則被認為該伺服器已經掛掉.你也可以自訂逾時參數.
你也可以配置多主多從的結構,例如:

[  'class' => 'yii\db\Connection',  // 配置主伺服器  'masterConfig' => [    'username' => 'master',    'password' => '',    'attributes' => [      // use a smaller connection timeout      PDO::ATTR_TIMEOUT => 10,    ],  ],  // 配置主伺服器組  'masters' => [    ['dsn' => 'dsn for master server 1'],    ['dsn' => 'dsn for master server 2'],  ],  // 配置從伺服器  'slaveConfig' => [    'username' => 'slave',    'password' => '',    'attributes' => [      // use a smaller connection timeout      PDO::ATTR_TIMEOUT => 10,    ],  ],  // 配置從伺服器組  'slaves' => [    ['dsn' => 'dsn for slave server 1'],    ['dsn' => 'dsn for slave server 2'],    ['dsn' => 'dsn for slave server 3'],    ['dsn' => 'dsn for slave server 4'],  ],]

上述配置制定了2個主伺服器和4個從伺服器.Connection組件也支援主伺服器的負載平衡和容錯移轉,與從伺服器不同的是,如果所有主伺服器都不可用,則會拋出異常.

注意:當你使用yii\db\Connection::masters來配置一個或多個主伺服器時,Connection中關於資料庫連接的其他屬性(例如:dsn,username, password)都會被忽略.
事務預設使用主伺服器的串連,並且在事務執行中的所有操作都會使用主伺服器的串連,例如:

// 在主伺服器串連上開始事務$transaction = $db->beginTransaction();try {  // 所有的查詢都在主伺服器上執行  $rows = $db->createCommand('SELECT * FROM user LIMIT 10')->queryAll();  $db->createCommand("UPDATE user SET username='demo' WHERE id=1")->execute();  $transaction->commit();} catch(\Exception $e) {  $transaction->rollBack();  throw $e;}

如果你想在從伺服器上執行事務操作則必須要明確地指定,比如:

$transaction = $db->slave->beginTransaction();

有時你想強制使用主伺服器來執行讀查詢,你可以調用seMaster()方法.

$rows = $db->useMaster(function ($db) {  return $db->createCommand('SELECT * FROM user LIMIT 10')->queryAll();});

你也可以設定$db->enableSlaves 為false來使所有查詢都在主伺服器上執行.

  • 操作資料庫模式
  • 獲得模式資訊

你可以通過 yii\db\Schema執行個體來擷取Schema資訊:

$schema = $connection->getSchema();

該執行個體包括一系列方法來檢索資料庫多方面的資訊:

$tables = $schema->getTableNames();

更多資訊請參考yii\db\Schema

修改模式

除了基礎的 SQL 查詢,yii\db\Command還包括一系列方法來修改資料庫模式:

  • 建立/重新命名/刪除/清空表
  • 增加/重新命名/刪除/修改欄位
  • 增加/刪除主鍵
  • 增加/刪除外鍵
  • 建立/刪除索引

使用樣本:

// 建立表$connection->createCommand()->createTable('post', [  'id' => 'pk',  'title' => 'string',  'text' => 'text',]);

完整參考請查看yii\db\Command.

SQL查詢樣本:

// find the customers whose primary key value is 10$customers = Customer::findAll(10);$customer = Customer::findOne(10);// the above code is equivalent to:$customers = Customer::find()->where(['id' => 10])->all();// find the customers whose primary key value is 10, 11 or 12.$customers = Customer::findAll([10, 11, 12]);$customers = Customer::find()->where(['IN','id',[10,11,12]])->all();// the above code is equivalent to:$customers = Customer::find()->where(['id' => [10, 11, 12]])->all();// find customers whose age is 30 and whose status is 1$customers = Customer::findAll(['age' => 30, 'status' => 1]);// the above code is equivalent to:$customers = Customer::find()->where(['age' => 30, 'status' => 1])->all();// use params binding$customers = Customer::find()->where('age=:age AND status=:status')->addParams([':age'=>30,':status'=>1])->all();// use index$customers = Customer::find()->indexBy('id')->where(['age' => 30, 'status' => 1])->all();// get customers count$count = Customer::find()->where(['age' => 30, 'status' => 1])->count();// add addition condition$customers = Customer::find()->where(['age' => 30, 'status' => 1])->andWhere('score > 100')->orderBy('id DESC')->offset(5)->limit(10)->all();// find by sql$customers = Customer::findBySql('SELECT * FROM customer WHERE age=30 AND status=1 AND score>100 ORDER BY id DESC LIMIT 5,10')->all();

修改:

// update status for customer-10$customer = Customer::findOne(10);$customer->status = 1;$customer->update();// the above code is equivalent to:Customer::updateAll(['status' => 1], 'id = :id',[':id'=>10]);

刪除:

// delete customer-10Customer::findOne(10)->delete();// the above code is equivalent to:Customer::deleteAll(['status' => 1], 'id = :id',[':id'=>10]);

--------------------------------使用子查詢------------------------------------------

$subQuery = (new Query())->select('COUNT(*)')->from('customer');// SELECT `id`, (SELECT COUNT(*) FROM `customer`) AS `count` FROM `customer`$query = (new Query())->select(['id', 'count' => $subQuery])->from('customer');

--------------------------------手寫SQL-------------------------------------------

// select$customers = Yii::$app->db->createCommand('SELECT * FROM customer')->queryAll();// updateYii::$app->db->createCommand()->update('customer',['status'=>1],'id=10')->execute();// deleteYii::$app->db->createCommand()->delete('customer','id=10')->execute();//transaction// outer $transaction1 = $connection->beginTransaction();try {  $connection->createCommand($sql1)->execute();  // internal  $transaction2 = $connection->beginTransaction();  try {    $connection->createCommand($sql2)->execute();    $transaction2->commit();  } catch (Exception $e) {    $transaction2->rollBack();  }  $transaction1->commit();} catch (Exception $e) {  $transaction1->rollBack();}

-----------------------------主從配置--------------------------------------------

[  'class' => 'yii\db\Connection',  // master   'dsn' => 'dsn for master server',  'username' => 'master',  'password' => '',  // slaves  'slaveConfig' => [    'username' => 'slave',    'password' => '',    'attributes' => [      // use a smaller connection timeout      PDO::ATTR_TIMEOUT => 10,    ],  ],  'slaves' => [    ['dsn' => 'dsn for slave server 1'],    ['dsn' => 'dsn for slave server 2'],    ['dsn' => 'dsn for slave server 3'],    ['dsn' => 'dsn for slave server 4'],  ],]

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.