温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

怎么在PHP中使用PDO操作sqlite数据库

发布时间:2021-05-31 16:23:55 阅读:383 作者:Leah 栏目:开发技术
亿速云云数据库,读写分离,安全稳定,弹性扩容,低至0.3元/天!! 点击查看>>

本篇文章给大家分享的是有关怎么在PHP中使用PDO操作sqlite数据库,小编觉得挺实用的,因此分享给大家学习,希望大家阅读完这篇文章后可以有所收获,话不多说,跟着小编一起来看看吧。

1、需求:

已知:

1)、一个json文件,里面是一个二维数组,数组解析出来为:

array (
   0 =>
   array (
    'title' => '九十九',
   ),
   1 =>
   array (
    'title' => '电脑九十九',
   ),
   2 =>
   array (
    'title' => '手机九十九',
   ),
   3 =>
   array (
    'title' => '手机电脑九十九',
   ),
);

2)、一个sqlite数据库文件 20180824.db 新建一个sqlite数据库文件

新建表 report

表字段 id words time

求:

把从json中查到的数据,在sqlite中检索,判断是否存在;
如果存在就给sqlite加上一个 word_sort字段,把title在文件中是第几个(一次递增,不是json文件数组的键值)写入到word_sort字段

思路:

① 获取jsonlist.json文件内容并json_decode($str,true)转为二维数组
② 连接sqlite表
try{}catch(){} 给表增加 word_sort字段
④ 把json文件中的数据数组化
⑤ 每次循环5000条json数据,用 IN 在report表中查询(title字段需要拼接)
⑥ 把查询出来的数据用 sql的批量跟新语句拼接
try{}catch(){}批量更新report表数据
⑧ echo输出运行结果

2、PHP代码(yaf框架):

<?php
/**
 * @todo 组词
 * Class CommunityController
 */
class CombinwordController extends Rest{
  /**
   * @todo 判断.json数据是否存在,存在把数据往前排
   * @linux 212 /usr/local/php7/bin/php /var/www/web/shop/public/cli.php request_uri="/v1/combinword/index"
   */
  public function indexAction(){
    set_time_limit 0 );  //设置时间不过时
    $data $this->getjson();  //获取json数据
    $dbfile_path = APP_PATH.'/data/combinword/20180824.db';
    $db new PDO("sqlite:{$dbfile_path}");
    //设置数据库句柄    属性 PDO::ATTR_ERRMODE:错误报告。   PDO::ERRMODE_EXCEPTION: 抛出 exceptions 异常。
    $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    //加combinword字段 START
    $add_filed 'word_sort';
    $add_filed_sql "alter table report add {$add_filed} TEXT(32)";
    try {
      $db->beginTransaction();//启动事务
      $db->exec($add_filed_sql);  //加字段
      $db->commit();//提交事务
    }catch(PDOException $e){
      //$e->getMessage();//获取错误信息。
      echo '字段已经存在'.PHP_EOL;
      $db->rollBack();//回滚,如果一个地方出现错误,回到总体操作之前。
    }
    //加combinword字段 END
    $addStep 5000;  //每次操作的数据
    $word_cnt 0;
    $succ_cnt 0;
    $sort 0;
    $total count($data);
    for $x=0$x<$total$x += $addStep ){
      $temp_json array_slice($data$x$addStep);  //批量操作 100条
      $temp_json array_column$temp_json"title" );
      $temp_json array_unique($temp_json);
      $temp_str $this->getStrByArr($temp_json);
      $temp_sql "select * from report where words IN ({$temp_str})";
      $res $db->query($temp_sql);
      $result $res->fetchAll(PDO::FETCH_ASSOC);  //获取数组结果集
      $words_result array_column($result'words'); //结果去重
      $unique_result array_unique($words_result);
      //var_export($unique_result);die;
      //批量更新 START
      $update_sql "UPDATE report SET {$add_filed} = CASE words ";
      foreach ($unique_result as $k => $v){
        $updateValue $v;
        $update_sql .= " WHEN '{$updateValue}' THEN ".$sort++;
      }
      $sort += count($unique_result);  //加上排序字段
      $update_sql_str $this->getStrByArr$unique_result );
      $update_sql .= " END WHERE words IN ({$update_sql_str})";
        //var_export($update_sql);die;
      try {
        $db->beginTransaction();//启动事务
        $cnt $db->exec($update_sql);  //加字段
        $db->commit();//提交事务
        $word_cnt += count($result);
        $succ_cnt += $cnt;
        echo "更新了[{".count($result)."}]个关键字,共影响了[{$cnt}]条数据 ".PHP_EOL;
      }catch(PDOException $e){
        //$e->getMessage();//获取错误信息。
        echo "批量更新失败 ".PHP_EOL;
        $db->rollBack();//回滚,如果一个地方出现错误,回到总体操作之前。
      }
      //批量更新END
    }
    echo "一共更新了[{$word_cnt}]个关键字,共影响了[{$succ_cnt}]条数据 ".PHP_EOL;
    die;
  }
  /**
   * @todo 根据数组返回拼接的字符串
   * @param unknown $temp_json 数组
   * @return string 字符串
   */
  function getStrByArr($temp_json){
    $temp_str '';
    $count count($temp_json);
    $lastValue end($temp_json);//var_export($lastValue);die;  //获取数组最后一个元素
    foreach ($temp_json as $k => $v){
      $next_str '';
      if($v != $lastValue ){  //不是最后一个
        $next_str ',';
      }else{
        $next_str '';
      }
      $temp_str .= "'".$v."'{$next_str}";
    }
    return $temp_str;
  }
  /**
   * @todo 获取json数据
   */
  public function getjson(){
    $filename = APP_PATH.'/data/combinword/jsonlist.json';
    $json file_get_contents($filename);
    $array json_decode($jsontrue);
    return $array;
  }
}

以上就是怎么在PHP中使用PDO操作sqlite数据库,小编相信有部分知识点可能是我们日常工作会见到或用到的。希望你能通过这篇文章学到更多知识。更多详情敬请关注亿速云行业资讯频道。

亿速云「云数据库 MySQL」免部署即开即用,比自行安装部署数据库高出1倍以上的性能,双节点冗余防止单节点故障,数据自动定期备份随时恢复。点击查看>>

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI

开发者交流群×