thinkphp5.0 数据库基本操作(一)

链接数据库

一共有三种模式,一般第一种就够了

  • 第一种直接配置application里面的database.php文件
// 服务器地址
'hostname'        => '127.0.0.1',
// 数据库名
'database'        => 'yachang',
// 用户名
'username'        => 'root',
// 密码
'password'        => 'root',
  • 第二种方法配置。使用数组在,方法前面配置
//在方法里面编写
<?php
    namespace app\index\controller;
    use think\Db;
    class Index extends Controller
    {
        public function index(Request $res)
        {
            Db::connect([
                // 服务器地址
                'hostname'    => '127.0.0.1',
                // 数据库名
                'database'    => 'thinkphp',
                // 数据库用户名
                'username'    => 'root',
                // 数据库密码
                'password'    => ''
            ]);
            //或者使用字符串
            Db::connect('mysql://root:1234@127.0.0.1:3306/thinkphp#utf8');
        }
    }
  • 第三种方法配置。利用模型在模型类创建数据库,然后在控制器中实例化模型
//在模型类创建数据库,然后在控制器中实例化模型
<?php
namespace namespace app\index\model;

use think\Model;
class Index extends Model
    {
         protected $connection = [
                // 服务器地址
                'hostname'    => '127.0.0.1',
                // 数据库名
                'database'    => 'thinkphp',
                // 数据库用户名
                'username'    => 'root',
                // 数据库密码
                'password'    => '',
            ];
    }
<?php
    namespace app\index\controller;
    use think\Db;
    use app\index\model\User;
    class Index
    {
        public function index()
        {
            $user = new User();
            dump($user);
        }
    }

使用原生sql语句查询

  1. 引入Db类就可以
  2. 执行query语句,复制查,还可以使用,execute语句,负责增删改。
  3. 还可以使用占位符,查看例子
Db::query('select * from think_user where id=?',[8]);
Db::execute('insert into think_user (id, name) values (?, ?)',[8,'thinkphp']);
//也支持命名占位符绑定,例如:
Db::query('select * from think_user where id=:id',['id'=>8]);
Db::execute('insert into think_user (id, name) values (:id, :name)',['id'=>8,'name'=>'thinkphp']);
//可以使用多个数据库连接,使用
Db::connect($config)->query('select * from think_user where id=:id',['id'=>8]);

获取最后执行的sql语句

//下面句子来执行,最后一条语句。
Db::getLastSql();
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

两个人的幸福online

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值