13
12

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

MySQLの複数行INSERTをする

Posted at

MySQLのbulk insertを手で書くのはまぁまぁめんどくさいなー、と思ったので何かライブラリないかなと思いつつ、bulkyというやつを見つけたりしたのですが、ちょっとコネクション周りのハンドリングとかクエリの実行周りは自前で扱いたい、という事情があったりして、bulk insert用のSQLの生成に特化したSQL_Insert_Multiを作ってみました。

こんな感じで使えます。

$builder = new SQL_Maker_InsertMulti("your_table", array('fields' => array(
    'id' => \PDO::PARAM_INT,
    'name' => \PDO::PARAM_STR,
    'created_at' => \PDO::PARAM_STR,
)));
foreach ( $data as $row ) {
    $builder->bindRow(array(
        'id'            => $row['id'],
        'name'          => $row['name'],
        'created_at'    => $row['created_at'],
    );
}
$stmt = $pdo->prepare($builer->toQuery());
$builer->bindValues($stmt);
$stmt->execute();

toQueryしたときに呼びだし元のSQLコメントを生成したりしてくれます(オフにすることもできます)。

13
12
3

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
13
12

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?