LoginSignup
0
1

More than 1 year has passed since last update.

PDOを使用したバルクインサートのサンプルコード

Posted at

PDOを使用したバルクインサートのサンプルコード

  • CSVファイルを読み込み、CsvImportModel モデルの bulkinsert 関数を呼び出しバルクインサート処理を行うサンプルコードです。
  • $bulk_cnt にバルクインサートの単位を宣言します。
任意
// CSVファイルからのインポート処理
$handle = fopen($file_path, "r");
$bulk_cnt = 100; // バルクインサート設定値
$bulk_arr = array();
$lineNo = 1;
while (($fields = fgetcsv($handle)) != false) {
  // Log::debug("CSVデータ {$lineNo}行目:". print_r(mb_convert_encoding($fields, 'UTF-8', 'SJIS'),true));
  if ($lineNo !== 1) $bulk_arr[] = mb_convert_encoding($fields, 'UTF-8', 'SJIS'); // 1行目ヘッダースキップ
  $lineNo++;

  if (count($bulk_arr) >= $bulk_cnt) {
    $result = CsvImportModel::bulkinsert($dbh, $bulk_arr);
    if ($result === false) {
      Log::debug('バルクインサート処理エラーが発生しました。');
    }
    $bulk_arr = array();
  }
}
if (count($bulk_arr) > 0) {
  $result = CsvImportModel::bulkinsert($dbh, $bulk_arr);
  if ($result === false) {
    Log::debug('バルクインサート処理エラーが発生しました。');
  }
}
unset($bulk_arr);
fclose($handle);
  • CsvImportModel モデル
CsvImportModel
  /**
   * レコード挿入処理(バルクインサート対応版)
   * 
   * @param object $dbh
   * @param array $params
   * @return int,bool
   */
  public static function bulkinsert(&$dbh, $params) {
    $bulk_sql = array();
    $placeholder = array();
    for($i=0;$i<count($params);$i++) {
      $bulk_sql[] = <<< SQL
( 
  :column_hoge_{$i}                             -- ほげ
  , :column_fuga_{$i}                           -- ふが
  , :column_piyo_{$i}                           -- ぴよ
  , now()
  , now()
)
SQL;
      $placeholder[":column_hoge_{$i}"]           = !empty($params[$i][0])   ? $params[$i][0]   : NULL;
      $placeholder[":column_fuga_{$i}"]           = !empty($params[$i][1])   ? $params[$i][1]   : NULL;
      $placeholder[":column_piyo_{$i}"]           = !empty($params[$i][2])   ? $params[$i][2]   : NULL;
    }


    $sql = <<< SQL
INSERT 
INTO sample_table ( 
  column_hoge                                   -- ほげ
  , column_fuga                                 -- ふが
  , column_piyo                                 -- ぴよ
  , created
  , modified
) 
VALUES 
SQL;
    $sql .= implode(',', $bulk_sql);

    try {
      $stmt = $dbh->prepare($sql);
      $stmt->execute($placeholder);
    } catch (Exception $e) {
      report($e);
      return false;
    }
    return DB::getPdo()->lastInsertId();
  }
  • SQL
--
-- Table structure for table `sample_table`
--

DROP TABLE IF EXISTS `sample_table`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!50503 SET character_set_client = utf8mb4 */;
CREATE TABLE `sample_table` (
  `id` int unsigned NOT NULL AUTO_INCREMENT,
  `column_hoge` varchar(191) DEFAULT NULL COMMENT 'ほげ',
  `column_fuga` varchar(191) DEFAULT NULL COMMENT 'ふが',
  `column_piyo` varchar(191) DEFAULT NULL COMMENT 'ぴよ',
  `created` timestamp NULL DEFAULT CURRENT_TIMESTAMP,
  `modified` datetime DEFAULT NULL,
  PRIMARY KEY (`id`),
  INDEX `index_search` (`column_hoge`, `column_fuga`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8mb4 COMMENT='サンプルテーブル';
/*!40101 SET character_set_client = @saved_cs_client */;
0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1