PHP使用PDO操作sqlite数据库应用案例

yipeiwu_com6年前PHP代码库

本文实例讲述了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($json, true);
    return $array;
  }
}

更多关于PHP相关内容感兴趣的读者可查看本站专题:《PHP基于pdo操作数据库技巧总结》、《php+Oracle数据库程序设计技巧总结》、《PHP+MongoDB数据库操作技巧大全》、《php面向对象程序设计入门教程》、《php字符串(string)用法总结》、《php+mysql数据库操作入门教程》及《php常见数据库操作技巧汇总

希望本文所述对大家PHP程序设计有所帮助。

相关文章

PHP 导出Excel示例分享

下载PHPExcel_1.8.0_doc.zip http://phpexcel.codeplex.com/,将解压后的文件夹里的Classes上传到网站的根目录下,Classes目录内...

PHP基于闭包思想实现的BT(torrent)文件解析工具实例详解

本文实例讲述了PHP基于闭包思想实现的torrent文件解析工具。分享给大家供大家参考,具体如下: PHP对静态词法域的支持有点奇怪,内部匿名函数必须在参数列表后面加上use关键字,显式...

解析:使用php mongodb扩展时 需要注意的事项

最近在使用php的mongo 扩展进行数据统计计算,其中有一个时间戳字段,由于精确到了毫秒,长度有13位,但由于开始的时候是以字符串的形式存储:复制代码 代码如下:{ "_id" : O...

PHP访问数据库集群的方法小结

本文总结分析了PHP访问数据库集群的方法。分享给大家供大家参考,具体如下: 一般常见的有三种做法: 1、自动判断sql是否为读,来选择数据库的连接: 实例化php DB类的时候,需要一次...

php将字符串随机分割成不同长度数组的方法

本文实例讲述了php将字符串随机分割成不同长度数组的方法。分享给大家供大家参考。具体分析如下: 这里使用php对字符串在指定的长度范围内进行随机分割,把分割后的结果存在数组里面 fu...