您的位置:首页 > 编程语言 > PHP开发

Yii2中使用自定义的数据库

2016-05-20 13:49 691 查看
Yii2中关于数据库的配置在文件
config/db.php
中,一般情况下,我们只需要在这里填写我们数据库的host、dbname、username、password,我们就可以通过继承ActiveRecord的类访问我们的数据库数据。

获取数据库连接的方法也很简单:

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


有时我们可以还可能需要在访问默认数据库的基础上,临时使用别的数据库,来配合我们的默认数据库,这时我们就不能通过models文件夹中的各个类来做到这一点了。

这时我们可以使用yii\db\Connection来解决这个问题。一段简单的代码如下:

//创建一个自定义数据库连接
$connection = new Connection([
'dsn' => 'mysql:host=localhost;dbname=yii2_basic',
'username' => 'myusername',
'password' => 'mypassword',
]);
//打开
$connection->open();

//这里放置我们CRUD的操作
//

//关闭
$connection->close();


在open()和close()之间,我们就可以编写数据库的查询、插入、更新、删除操作。

查询数据

//打开
$connection->open();

$sql = "select * from book";
$command = $connection->createCommand($sql);

//查询多条数据
$books = $command->queryAll();
var_dump($books);
//查询一条数据
$book = $command->queryOne();
var_dump($book);

//关闭
$connection->close();


插入一条数据

//打开
$connection->open();

//通过sql语句插入一条数据
$sql = "insert into book values(null,'t-title','a-author','i-introduce',".time().");";
$command = $connection->createCommand($sql);
$affectRows = $command->execute();
echo $affectRows."\n";

//通过insert函数插入一条数据
$command = $connection->createCommand();
$affectRows = $command->insert("book", [
'title'=>'t-title',
'author'=>'a-author',
'introduce'=>'i-introduce',
'create_time'=>time(),
])->execute();
echo $affectRows."\n";

//关闭
$connection->close();


更新一条数据

//打开
$connection->open();

//通过sql语句更新一条数据
$sql = "update book set title='new-title' where id=1;";
$command = $connection->createCommand($sql);
$affectRows = $command->execute();
echo $affectRows."\n";

//通过update函数更新一条数据
$command = $connection->createCommand();
$affectRows = $command->update("book",
[
"title" => "new-title"
],
[
"id" => 2
]
)->execute();
echo $affectRows."\n";

//关闭
$connection->close();


删除一条数据

//打开
$connection->open();

//通过sql语句删除一条数据
$sql = "delete from book where id=1;";
$command = $connection->createCommand($sql);
$affectRows = $command->execute();
echo $affectRows."\n";

//通过delete函数删除一条数据
$command = $connection->createCommand();
$affectRows = $command->delete("book",[
"id"=>2,
])->execute();
echo $affectRows."\n";

//关闭
$connection->close();


参考

http://www.yiichina.com/doc/api/2.0/yii-db-connection

http://www.yiichina.com/doc/guide/2.0/db-dao
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  yii2 connection 数据库