前言[随时更新]
MySQL快速复习
MySQL原生查询
选择数据表
删除数据
聚合查询
时间查询
视图查询
子查询
总结/参考
创建一张数据表:tp5_staff (命名规则:数据库名 _ 表名)

静态方法:指不需要实例化对象,直接用类调用的方法;
功能:完成数据库初始化,并取得数据库实例;
备注:该方法为静态方法,可被该类所有实例(对象)所共享;

我们现在工作在:app/index/controller/Index 控制器的index方法;
文件位置:/application/index/controller/Index.php;
控制器Index文件内容:
<?php
namespace app\index\controller;
use think\Db;
use think\Debug;
class Index{
public function index(){
//设置数据库配置参数数组
$dbConfig = [
// 数据库类型
'type' => 'mysql',
// 数据库连接DSN配置
'dsn' => '',
// 服务器地址
'hostname' => 'localhost',
// 数据库名
'database' => 'tp5',
// 数据库用户名
'username' => 'root',
// 数据库密码
'password' => 'root',
// 数据库连接端口
'hostport' => '3306',
// 数据库连接参数
'params' => [],
// 数据库编码默认采用utf8
'charset' => 'utf8',
// 数据库表前缀
'prefix' => 'tp5_',
];
//将配置数组做为connect()的参数传入
$result=Db::connect($dbConfig) //创建数据库连接
->table('tp5_staff') //选择数据表
->select(); //输出结果集
//以二维数据方式返回结果集
Debug::dump($result);
}
}
<?php
namespace app\index\controller;
use think\Db;
use think\Debug;
class Index{
public function index(){
//数据库连接配置字符串
$dbConfig = 'mysql://root:root@localhost:3306/tp5#utf8';
//将配置字符串做为connect()的参数传入
$result=Db::connect($dbConfig) //创建数据库连接
->table('tp5_staff') //选择数据表
->select(); //输出结果集
//以二维数据方式返回结果集
Debug::dump($result);
}
}
1、数组方式配置:可以设置更多的信息,如表前缀等;
2、字符串方式配置:只可设置必须的连接信息,简洁、灵活。