3 连接数据库(上)

3.1 设置数据库驱动

因为ThinkPHP内置了抽象数据库访问层,把不同的数据库操作封装起来,我们只需要使用公共的Db类进行操 作,而无需针对不同的数据库写不同的代码和底层实现,Db类会自动调用相应的数据库驱动来处理。采用 PDO方式,目前包含了Mysql、SqlServer、PgSQL、Sqlite等数据库的支持。

所以使用前要确保数据库驱动设置:

打开php的安装目录下的php.ini,搜索;extension=php_pdo_mysql.dll,去掉前面的;

保存并重启apache。

3.2 配置数据库连接文件

打开thinkphp安装目录tp5,打开application/database.php文件

按照注释修改数据库的连接信息

 'mysql',
    // 服务器地址
    'hostname'        => '127.0.0.1',
    // 数据库名
    'database'        => 'tp5_mysql',
    // 用户名
    'username'        => 'root',
    // 密码
    'password'        => 'root',
    // 端口
    'hostport'        => '',
    // 连接dsn
    'dsn'             => '',
    // 数据库连接参数
    'params'          => [],
    // 数据库编码默认采用utf8
    'charset'         => 'utf8',
    // 数据库表前缀
    'prefix'          => '',
    // 数据库调试模式
    'debug'           => true,
    // 数据库部署方式:0 集中式(单一服务器),1 分布式(主从服务器)
    'deploy'          => 0,
    // 数据库读写是否分离 主从式有效
    'rw_separate'     => false,
    // 读写分离后 主服务器数量
    'master_num'      => 1,
    // 指定从服务器序号
    'slave_no'        => '',
    // 自动读取主库数据
    'read_master'     => false,
    // 是否严格检查字段是否存在
    'fields_strict'   => true,
    // 数据集返回类型
    'resultset_type'  => 'array',
    // 自动写入时间戳字段
    'auto_timestamp'  => false,
    // 时间字段取出后的默认时间格式
    'datetime_format' => 'Y-m-d H:i:s',
    // 是否需要进行SQL性能分析
    'sql_explain'     => false,
];

为了便于测试,这里需要新一个数库库tp5_mysql,并新建表think_data

CREATE TABLE `think_data` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(255) NOT NULL,
  `status` int(255) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8

3.3 通过原生语句操作数据表

这里我新建了一个控制器app/test/Abc.php文件,方便测试

通过之前设置的虚拟主机,现在访问 http://www.tp5.com/index.php/test/abc/db 如果能得到数据,那么测试文件设置无误。

连接数据库前要引入Db类

use think\Db;

配置了数据库连接信息后,我们就可以直接使用数据库运行原生SQL操作了,支持 query (查询操作)和 execute (写入操作)方法,并且支持参数绑定

Db::execute('insert into think_data(name,status) values("老王",1)');
$res=Db::query('select * from think_data');
dump($res);

全部代码:

namespace app\test\controller;
use think\Db;
class Abc
{
    public function db()
    {
        // Db::execute('insert into think_data(name,status) values("老王",1)'); //插入数据
        // Db::execute('delete from think_data where id in (4,5)'); //删除操作
        // Db::execute('update think_data set name="老周",status=3 where id=2'); //修改数据
        $res=Db::query('select * from think_data'); // 查询数据
        dump($res);
        //使用占位符操作
        Db::execute('insert into think_data values(?,?,?)',[null,'小王',2]);
        Db::execute('insert into think_data(name,status) values(:name,:status)',['name'=>'小周','status'=>2]);
        $res2=Db::query('select * from think_data where id=:id',['id'=>2]);
        dump($res2);
        }
}

你可能感兴趣的:(3 连接数据库(上))