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 基础查询
一旦有了连接实例就可以通过[[yii\db\Command]]执行 SQL 查询。
SELECT 查询
查询返回多行:
$command = $connection->createCommand('SELECT * FROM post'); $posts = $command->queryAll();
返回单行:
$command = $connection->createCommand('SELECT * FROM post WHERE id=1'); $post = $command->queryOne();
查询多行单值:
$command = $connection->createCommand('SELECT title FROM post'); $titles = $command->queryColumn();
查询标量值/计算值:
$command = $connection->createCommand('SELECT COUNT(*) FROM post'); $postCount = $command->queryScalar();
UPDATE, INSERT, DELETE 更新、插入和删除等
如果执行 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['i