7
3

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.

動的SOQLの作り方

Last updated at Posted at 2018-10-03

SOQLを動的に作りたい場面があったので、方法と注意点について記事化

動的にSOQLを作成して、レコードを取得したいときは、
クエリ文字列を作成してDatabase.query() に渡してあげる

String soql = 'SELECT Id FROM Account WHERE NAME ='+ VALUE;
List<Account> accountList = Database.query(soql);

ここで注意
↑みたいに単純にクエリ文字列に変数を繋げるとSQOLインジェクションが起きるらしいので、
escapeSingleQuotes()で変数を文字列として処理する

結論

↓みたいにする

String soql = 'SELECT Id FROM Account WHERE NAME = '+ String.escapeSingleQuotes(VALUE);
List<Account> accountList = Database.query(soql);

ポイント

  • 動的SOQLはSOQLインジェクションに注意
    • scapeSingleQuotes()使う
  • 静的SOQLはバインド変数を使っているのでSOQLインジェクションを防げるらしい

参考

7
3
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
7
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?