Skip to content

Instantly share code, notes, and snippets.

@takenoco82
Created August 10, 2019 13:36
Show Gist options
  • Save takenoco82/78a5c346e8f1154c27121d97335f2361 to your computer and use it in GitHub Desktop.
Save takenoco82/78a5c346e8f1154c27121d97335f2361 to your computer and use it in GitHub Desktop.

MySQLでSQLにパラメータを利用する

概要

  • Prepared Statement を使う
  • ユーザー定義変数を使ってSQL文を作成し、Prepared Statement を実行する

ユーザーを作成するサンプル

SET @db_username = 'user_name';
SET @db_password = 'password';

--  DROP USER IF EXISTS 'user_name';
SET @drop_user = CONCAT("DROP USER IF EXISTS '", @db_username, "';");
PREPARE stmt FROM @drop_user;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;

--  CREATE USER user_name@`%` IDENTIFIED BY 'password';
SET @create_user = CONCAT("CREATE USER ", @db_username, "@`%` IDENTIFIED BY '", @db_password, "';");
PREPARE stmt FROM @create_user;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;

--  GRANT ALL PRIVILEGES ON *.* TO `user_name`@`%`;
SET @grant = CONCAT("GRANT ALL PRIVILEGES ON *.* TO ", @db_username, "@`%`;");
PREPARE stmt FROM @grant;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;

参考資料

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment