Yii2中使用自定义的数据库
2016-05-20 13:49
691 查看
Yii2中关于数据库的配置在文件
获取数据库连接的方法也很简单:
有时我们可以还可能需要在访问默认数据库的基础上,临时使用别的数据库,来配合我们的默认数据库,这时我们就不能通过models文件夹中的各个类来做到这一点了。
这时我们可以使用yii\db\Connection来解决这个问题。一段简单的代码如下:
在open()和close()之间,我们就可以编写数据库的查询、插入、更新、删除操作。
http://www.yiichina.com/doc/guide/2.0/db-dao
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-connectionhttp://www.yiichina.com/doc/guide/2.0/db-dao
相关文章推荐
- Android之获取手机上的图片和视频缩略图thumbnails
- 数据库链接字符串查询网站
- DB2实例管理
- DB2实例管理
- 保障MySQL数据安全的14个最佳方法
- mysql问答汇集
- 第三章 数据库备份和还原
- 创建一个空的IBM DB2 ECO数据库的方法
- Access 2000 数据库 80 万记录通用快速分页类
- 开通一个数据库失败的原因的和解决办法
- 一个简单的asp数据库操作类
- CentOS下DB2数据库安装过程详解
- EasyASP v1.5发布(包含数据库操作类,原clsDbCtrl.asp)第1/2页
- sql2008 还原数据库解决方案
- Oracle 数据库自动存储管理-安装配置
- Oracle数据库执行脚本常用命令小结
- Oracle 数据库 临时数据的处理方法
- 数据库分页查询语句数据库查询
- 最近比较流行的数据库挂马