C Sharpとデータベース - ストアドプロシージャ

提供:MochiuWiki - SUSE, Electronic Circuit, PCB
ナビゲーションに移動 検索に移動

概要

C#からSQL Serverに設定したストアドプロシージャを実行する時のサンプルコードを記載する。


サンプルコード

SQL Server ストアド プロシージャ

使用するストアドプロシージャは、引数無しのSELECT文の結果を返すだけのストアドプロシージャである。

 CREATE PROCEDURE [dbo].[StoredProcedure_Sample]
 AS
 BEGIN
    SET NOCOUNT ON;
 
    SELECT * FROM sys.objects
 END


C# サンプルコード

SELECT文の結果をSqlDataAdapterのFillメソッドでDataSetに格納する。
DataSetのTablesは配列になっているため、ストアドプロシージャがSELECT文の結果を複数返す場合にも対応可能である。

 using System;
 using System.Configuration;
 using System.Data;
 using System.Data.SqlClient;
 
 public void GetData()
 {
    var table = new DataTable();
 
    // 接続文字列の取得(データソースの直接指定)
    var connectionString = @"SERVER=LOCALHOST\SQLEXPRESS;UID=hoge;PWD=piyo;DATABASE=D_Sample";
 
    // 接続文字列の取得(設定ファイル(xml形式)から取得)
    var connectionString = ConfigurationManager.ConnectionStrings["sqlsvr"].ConnectionString;
 
    using (var connection = new SqlConnection(connectionString))
    using (var command = connection.CreateCommand())
    {
        try
        {
            // データベースの接続開始
            connection.Open();
 
            // ストアドプロシージャの指定
            command.CommandType = CommandType.StoredProcedure;
 
            // ストアドプロシージャ名の指定
            command.CommandText = "StoredProcedure_Sample";
 
            // ストアドプロシージャを実行して結果をdataSetへ格納
            var dataSet = new DataSet();
            using (var adapter = new SqlDataAdapter(command))
            {
               adapter.Fill(dataSet);
            }
 
            // 結果を表示
            this.dataGridView1.DataSource = dataSet.Tables[0];
        }
        catch (Exception exception)
        {
            Console.WriteLine(exception.Message);
            throw;
        }
        finally
        {   // データベースの接続終了
            connection.Close();
        }
    }
 }