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:[email protected]: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();

猜你喜欢

转载自blog.csdn.net/weixin_42249565/article/details/80467360