前言[随时更新]
MySQL快速复习
MySQL原生查询
选择数据表
删除数据
聚合查询
时间查询
视图查询
子查询
总结/参考
准备工作:在当前模块index下面创建配置文件 :config.php
index模块中的config.php 内容如下:
<?php
return [
//数据库配置1
'db_config1' =>
[
// 数据库类型
'type' => 'mysql',
// 服务器地址
'hostname' => 'localhost',
// 数据库名
'database' => 'tp5',
// 数据库用户名
'username' => 'root',
// 数据库密码
'password' => 'root',
// 数据库编码默认采用utf8
'charset' => 'utf8', // 数据库表前缀
'prefix' => 'tp5_',
],
//数据库配置2
'db_config2' => 'mysql://root:root@localhost:3306/tp5#utf8',
];
数组中有二个元素,每个数组元素对应一个数据库配置项,为了便于测试,这里采用了相同的配置(数据名、用户名、密码,编码、前缀等)
这时,在Index控制器中加入如下代码:
<?php
namespace app\index\controller;
use think\Db;
use think\Debug;
class Index{
public function index(){
Debug::dump(Db::connect('db_config1')->table('tp5_staff')->select());
}
}
在浏览器中地址栏输入:tp5.com/index/index/index 查询结果如下:
再次修改控制器Index.php,使用配置2:
<?php
namespace app\index\controller;
use think\Db;
use think\Debug;
class Index{
public function index(){
Debug::dump(Db::connect('db_config1')->table('tp5_staff')->select());
}
}
<?php
namespace app\index\controller;
use think\Db;
class Index{
public function index(){
//创建数据库连接对象
$db=Db::connect('db_config2');
//获取结果集
$result = $db
-> table('tp5_staff') //选择 tp5_staff表
-> select(); //获取全部数据
//输出全部数据
dump($result);
}
}
运行效果与上面是完全一致的。
1、代码清晰、结构合理,是做为一名程序员必备的基本素质。
2、为了使代码更具有可读性,更易于维护,多写几行代码,多写点注释,是非常值得的。
3、我们以后的教学中,更多的采用这种方式教学。