「C Sharpとデータベース - パラメタライズドクエリ」の版間の差分

提供:MochiuWiki : SUSE, EC, PCB
ナビゲーションに移動 検索に移動
(Wiki がページ「SQL Serverにパラメタライズドクエリを実行する」を「C Sharpとデータベース - パラメタライズドクエリ」に、リダイレクトを残さずに移動しました)
(文字列「source lang」を「syntaxhighlight lang」に置換)
7行目: 7行目:


== パラメタライズドクエリのサンプルコード ==
== パラメタライズドクエリのサンプルコード ==
  <source lang="cpp">
  <syntaxhighlight lang="cpp">
  using System;
  using System;
  using System.Configuration;
  using System.Configuration;

2021年11月18日 (木) 14:02時点における版

概要

セキュリティ上の対策として、パラメタライズドクエリ(パラメタ化クエリ、パラメータクエリとも呼ばれる)を利用することが多い。
このパラメタライズドクエリ、言語やデータベースによって指定方法が異なる。

C#でSQL Serverに対してパラメタライズドクエリを利用する際は、@パラメータ名でパラメータ指定する。
Commandを再利用する場合、パラメータが保存されたままとなるので、パラメータ指定するキー名が被らないように注意する。

パラメタライズドクエリのサンプルコード

<syntaxhighlight lang="cpp">
using System;
using System.Configuration;
using System.Data.SqlClient;

public void Insert1(string id, string password, string role)
{
   // 接続文字列の取得
   var connectionString = ConfigurationManager.ConnectionStrings["sqlsvr"].ConnectionString;

   using (var connection = new SqlConnection(connectionString))
   using (var command = connection.CreateCommand())
   {
       try
       {
           // データベースの接続開始
           connection.Open();

           // SQLの準備
           command.CommandText = @"INSERT INTO T_USER (ID, PASSWORD, ROLE_NAME) VALUES (@ID, @PASSWORD, @ROLE_NAME)";
           command.Parameters.Add(new SqlParameter("@ID", id));
           command.Parameters.Add(new SqlParameter("@PASSWORD", password));
           command.Parameters.Add(new SqlParameter("@ROLE_NAME", role));

           // SQLの実行
           command.ExecuteNonQuery();
       }
       catch (Exception exception)
       {
           Console.WriteLine(exception.Message);
           throw;
       }
       finally
       {
           // データベースの接続終了
           connection.Close();
       }
   }
}
</source>