ThinkPHP5数据库实例详解 / Db类静态方法connect()

Db类静态方法connect()

二、Db类的静态方法connect()

  • 创建一张数据表:tp5_staff (命名规则:数据库名 _ 表名)

    • 表中内容如下:

  • 静态方法:指不需要实例化对象,直接用类调用的方法;

  • 功能:完成数据库初始化,并取得数据库实例;

  • 备注:该方法为静态方法,可被该类所有实例(对象)所共享;

  • 该方法,根据参数不同,有二种实现方案:

1、数组作为参数

  • 我们现在工作在: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);
    }
}

2、字符串做为参数

  • 基本格式:数据库类型://用户名:密码@数据库地址:数据库端口/数据库名#字符集
  • 文件位置:/application/index/controller/Index.php
  • 控制器Index文件内容:
<?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);
    }
}
  • 以上二种参数传入connect()方法后,查询结果是完全一样的:

总结:

1、数组方式配置:可以设置更多的信息,如表前缀等;
2、字符串方式配置:只可设置必须的连接信息,简洁、灵活。