tp5-5 连接,操作,调试数据库

使用动态连接& 模型类定义

 当模型操作的时候会自动连接给定的数据库连接,而不是配置文件中设置的默认连接信息

1 在 应用配置文件config.php  里添加数组配置

 

  1. <?
  2.     'machine'=> [
  3.             // 数据库类型
  4.             'type'        => 'mysql',
  5.             // 服务器地址
  6.             'hostname'    => '127.0.0.1',
  7.             // 数据库名
  8.             'database'    => 'machine',
  9.             // 数据库用户名
  10.             'username'    => 'root',
  11.             // 数据库密码
  12.             'password'    => 'root',
  13.             // 数据库编码默认采用utf8
  14.             'charset'     => 'utf8',
  15.             // 数据库表前缀
  16.             'prefix'      => '',
  17.         ],
  18.     'rbac'=>'mysql://root:root@localhost:3306/rbac#utf8',

 

动态连接:在方法里应用

 

 
 
  1. <?
  2. $machine = Db::connect('machine')->query('select * from admin_users where id=1');
  3.  
  4. $rbac = Db::connect('rbac')->query('select * from role where id=1');

模型类定义:在模型里应用

  1. <?php
  2. namespace app\admin\model;
  3.  
  4. use think\Model;
  5. use think\Db;
  6.  
  7. class Access extends Model
  8. {
  9. protected $connection = [
  10.             // 数据库类型
  11.             'type'        => 'mysql',
  12.             // 服务器地址
  13.             'hostname'    => '127.0.0.1',
  14.             // 数据库名
  15.             'database'    => 'rbac',
  16.             // 数据库用户名
  17.             'username'    => 'root',
  18.             // 数据库密码
  19.             'password'    => 'root',
  20.             // 数据库编码默认采用utf8
  21.             'charset'     => 'utf8',
  22.             // 数据库表前缀
  23.             'prefix'      => '',
  24.         ];
  25.     
  26. }

4 在方法里使用此模型类

 
 
  1. <?
  2. public function useMode()
  3. {
  4. $a = new Access;
  5. dump($a::all());
  6. dump($a->query('select * from role where id=1'));
  7. $res = $a->table('access')->where('id','1')->find();
  8. dump($res);
  9.  
  10. }

 

1 使用数据表前缀和未使用的区别

未使用前缀 直接table 里写表名

  1. <?
  2. use think\Db;
  3. 查询一条数据使用:
  4. // table方法必须指定完整的数据表名
  5. Db::table('think_user')->where('id',1)->find();
  6. find 方法查询结果不存在,返回 null
  7.  
  8. 查询数据集使用:
  9. Db::table('think_user')->where('status',1)->select();
  10. select 方法查询结果不存在,返回空数组

使用了前缀的话 name会拼接  参数 数据库表前缀  'prefix' => 'think_',  组成一个table名字

 
 
  1. <?
  2. Db::name('user')->where('id',1)->find();
  3. Db::name('user')->where('status',1)->select();

 

2 打印sql 语句

  1. <?
  2. //-------------------------------
  3. // 第一种                       |
  4. //-------------------------------
  5. dump(Db::getLastSql());
  6.  
  7. //-------------------------------
  8. // 第二种添加 ->fetchSql()      |
  9. //-------------------------------
  10. $data = Db::table('user')->fetchSql()->where($map)->select(); 

 

3 操作sql 语句 1 

execute 操作增删改 返回的均是影响行数

 


a 增

 
 
  1. <?
  2. public function insert()
  3. {
  4. $res = Db::execute("insert into user(username,password) values('小黄','12345')");
  5. $res = Db::execute("insert into user(username,password) values(:name,:pa)",['name'=>'大礼','pa'=>'666']);
  6. dump($res);
  7. }

 

b 删

 

  1. <?
  2. public function delete()
  3. {
  4.    $res = Db::execute('delete from user where id >:id',['id'=>6]);
  5.    dump($res);
  6. }

 

 

c 改

 

 
 
  1. <?
  2. public function update()
  3. {
  4. $res = Db::execute('update user set username=:name where id >=:id',['id'=>5,'name'=>'史泰龙']);
  5.     dump($res);
  6. }

 

 

d 查

  1. <?
  2. think\Db;
  3. //使用占位符
  4. $result = Db::query('select * from think_user where id>? and id<?',[0,3]);
  5.  
  6. $result = Db::query('select * from user where id>:id1 and id<=:id2',['id1'=>0,'id2'=>3]);

 

 

4 使用查询构造器

Db类 是单例模式  db助手函数则不是每次使用将重复链接数据库

->find()是一条数据

->select()是数据集合

查询

1 查询集合和单一数据

   数组查询

    等于

    大于等于(注意同字段加条件要另起一个where( ))

    like模糊查询

    whereOr 或者

   limit 2

   limit 2,3 

   order 排序

   设置 查询字段 和 起别名

          使用count sum 函数 尽量用 find( )

          field第二参数true   排除字段

  column 代替select 和find

  page 分页

  group 和  having 分组聚合的条件选

  join  可放数组里

  DISTINCT 方法用于返回唯一不同的值 

  cache 缓存有效期是由默认的缓存配置参数决定的,但cache方法可以单独指定

 fetchSql用于直接返回SQL而不是执行查询

 
 
  1. <?php
  2. use think\Db;
  3. $map['id']  = ['>',1];
  4. $map['username'] = ['like','%u%'];
  5. $map['status'] = 0;
  6. // 把查询条件传入查询方法
  7. $data = Db::table('user')->where($map)->select(); 
  8.  
  9.  
  10. $data = Db::table('user')->where('id','10')->select();
  11.  
  12. // 也可以使用助手函数
  13. $data = db('user')->where('id','10')->select();
  14. $data = db('user')->where('id','>=','4')->where('id','<','9')->select();
  15. $data = db('user')->where('username','like','%u%')->where('id','<','6')->select();
  16. $data = db('user')->where('id','>=','6')->whereOr('id','<=','2')->select();
  17. $data fetchSql= db('user')->where('id','>=','6')->whereOr('id','<=','2')->limit(2)->select();
  18. $data = db('user')->where('id','>=','6')->whereOr('id','<=','1')->limit(2,3)->select();
  19. $data = db('user')->where('id','>=','1')->whereOr('id','<=','1')->limit(2,6)->order('id','desc')->select();
  20. $data = db('user')->field('username nameis,count(*) as cou')->where('id','>=','1')->whereOr('id','<=','1')->limit(2,6)->order('id','desc')->select();
  21. $data = db('user')->field('count(*) as cou')->where('id','>=','1')->whereOr('id','<=','1')->limit(2,6)->order('id','desc')->find();
  22. $data = db('user')->field('username,password',true)->select();
  23.  
  24. //下面 column一个值是二维,两个值时首个做键二维,三个值首个值做键,三维
  25. $data = db('user')->where('username','like','%u%')->column('username,password,status');
  26. /** page 分页
  27.  *  page(1,5)  第一页:第一条到第五条
  28.  *  page(2,5)  第二页:第六条到第十条
  29.  */
  30. $data = db('user')->page('2,5')->select();
  31. //group 分组  和 having 分组聚合后的选择
  32. $data = Db::table('user')->field('status,count(*) as co')->group('status')->select();
  33. $data = Db::table('user')->field('status,count(*) as co')->group('status')->having('co > 2')->select();
  34.  
  35. //join
  36. $data = Db::table('user')->alias('u')
  37.   ->where('u.id=:iidd',['iidd'=>1])
  38.   ->field('u.username,ur.role_id,r.name')
  39.   ->join('user_role ur','ur.uid=u.id')
  40.   ->join('role r','r.id=ur.role_id')
  41.   ->select();
  42.   
  43. // DISTINCT 方法用于返回唯一不同的值 
  44. Db::table('user')->distinct(true)->field('username')->select();
  45. //缓存
  46. $data = Db::table('user')->where('id','10')->cache(true)->select();
  47. $data = Db::table('user')->where('id','10')->cache(60)->select();  //缓存60秒
  48.  
  49. // cache方法可以指定缓存标识:
  50. $data = Db::table('user')->cache('key',60)->find();
  51. $data = \think\Cache::get('key');
  52.  
  53. //fetch
  54. $data = Db::table('user')->fetchSql(true)->find(1);
  55. 输出result结果为: SELECT * FROM think_user where id = 1
  56.  
  57.  
  58.  

 

新增

1 使用返回自增主键函数getLastInsID() 必须要跟插入数据函数insert($data);一起执行

2 或者使用  insertGetId 代替 getLastInsID() 和insert  直接返回主键

 

  1. <strong><?php
  2. $data = [
  3.       'username'=>'张华',
  4.       'password'=>'5555'
  5.         ];
  6. $resutl = Db::table('user')->insert($data);
  7. //返回自增主键  
  8. $userId = Db::name('user')->getLastInsID();
  9. //也可以直接自增返回
  10. $resutl = Db::table('user')->insertGetId($data);
  11.  
  12. //一次插入多条数据
  13. $data = [
  14.             [ 'username'=>'李二','password'=>'5555'],
  15.             [ 'username'=>'王大','password'=>'5555'],
  16.         ];
  17. $resutl = Db::table('user')->insertAll($data);
  18.  </strong>

 

更新

 
 
  1. <?php
  2. $data = [
  3.             'username'=>'二狗','password'=>'erere',
  4.          ];
  5. $resutl = Db::table('user')->where('id', 2)->update($data);

删除p;\

 

  1. <?php
  2. //根据主键删除
  3. $result = Db::table('user')->delete([12,13,14]);
  4. //根据条件删除
  5. $result = Db::table("user")->where('password','=','1111111')->delete();

 

 

聚合函数

1 count( ) 统计

2 max( ) 最大值

3 min( ) 最小值

4 avg( ) 平均值

5 sum( ) 求和

 
 
  1. <?php
  2. $result = Db::table('user')->where('status','=','0')->count();
  3.  
  4. $result = Db::table('user')->where('status','=','0')->avg('id');

 

 时间表达式

  1. <?php
  2. 使用whereTime方法
  3. whereTime方法提供了日期和时间字段的快捷查询,示例如下:
  4.  
  5. // 大于某个时间
  6. Db::table('think_user')->whereTime('birthday', '>=', '1970-10-1')->select();
  7. // 小于某个时间
  8. Db::table('think_user')->whereTime('birthday', '<', '2000-10-1')->select();
  9. // 时间区间查询
  10. Db::table('think_user')->whereTime('birthday', 'between', ['1970-10-1', '2000-10-1'])->select();
  11. // 不在某个时间区间
  12. Db::table('think_user')->whereTime('birthday', 'not between', ['1970-10-1', '2000-10-1'])->select();
  13. 时间表达式
  14. 还提供了更方便的时间表达式查询,例如:
  15.  
  16. // 获取今天的博客
  17. Db::table('think_blog') ->whereTime('create_time', 'today')->select();
  18. // 获取昨天的博客
  19. Db::table('think_blog')->whereTime('create_time', 'yesterday')->select();
  20. // 获取本周的博客
  21. Db::table('think_blog')->whereTime('create_time', 'week')->select();   
  22. // 获取上周的博客
  23. Db::table('think_blog')->whereTime('create_time', 'last week')->select();    
  24. // 获取本月的博客
  25. Db::table('think_blog')->whereTime('create_time', 'month')->select();   
  26. // 获取上月的博客
  27. Db::table('think_blog')->whereTime('create_time', 'last month')->select();      
  28. // 获取今年的博客
  29. Db::table('think_blog')->whereTime('create_time', 'year')->select();    
  30. // 获取去年的博客
  31. Db::table('think_blog')->whereTime('create_time', 'last year')->select();     
  32. 如果查询当天、本周、本月和今年的时间,还可以简化为:
  33.  
  34. // 获取今天的博客
  35. Db::table('think_blog')->whereTime('create_time', 'd')->select();
  36. // 获取本周的博客
  37. Db::table('think_blog')->whereTime('create_time', 'w')->select();   
  38. // 获取本月的博客
  39. Db::table('think_blog')->whereTime('create_time', 'm')->select();   
  40. // 获取今年的博客
  41. Db::table('think_blog')->whereTime('create_time', 'y') ->select();    
  42. V5.0.5+版本开始,还可以使用下面的方式进行时间查询
  43.  
  44. // 查询两个小时内的博客
  45. Db::table('think_blog')->whereTime('create_time','-2 hours')->select();

 闭包查询

 

 
 
  1. <strong><?php
  2. $id = input($id);
  3. $result = Db::table('banner_item')
  4.         ->where(function($query) use ($id){
  5.             $query->where('banner_id','=',$id);
  6.         })
  7.         ->select();</strong>

 

 5 事务机制

mysql事务 必须要求数据库是 innodb 引擎

 自动控制事务

  1. <?php
  2. use think\Db;
  3. // 启动事务
  4.         Db::startTrans();
  5.         try{
  6.             $a = Db::table('user')->delete(29);
  7.             if(!$a)throw new \Exception('删除没成功');
  8.             
  9.            
  10.            $b = Db::table('user')->delete(90);
  11.             
  12.             if(!$b)throw new \Exception('插入没成功');
  13.             // 提交事务
  14.             Db::commit();
  15.             echo '完成';
  16.             
  17.         } catch (\Exception $e) {
  18.             echo $e->getMessage();
  19.             // 回滚事务
  20.             Db::rollback();
  21.         }
  22. //更简洁
  23.         Db::startTrans();
  24.         $a = Db::table('user')->delete(26);
  25.         $b = Db::table('user')->delete(90);
  26.          if($a && $b)
  27.         {
  28.             Db::commit();
  29.         }
  30.         else
  31.         {
  32.             Db::rollback();
  33.         }
  34.         echo '完成';

 调试数据库

 

application/database.php 开启调试

 
 
  1. // 数据库调试模式
  2.     'debug'           => true,

 application/config.php   开启  日志

 
 
  1.  
  2. // 开启日志
  3.     'log'                    => [
  4.         // 日志记录方式,内置 file socket 支持扩展
  5.         'type'  => 'file',//正常File是开启的  test是关闭
  6.         // 日志保存目录
  7.         'path'  => LOG_PATH,
  8.         // 日志记录级别
  9.         'level' => ['sql'],
  10.     ],

猜你喜欢

转载自blog.csdn.net/qq_19004627/article/details/81010071
今日推荐