SQL ServerにWindows認証で接続する方法とデータをDataGridViewで一覧表示する方法を説明します。
Windows認証を使った接続
パッケージSystem.Data.SqlClientをインストール
SQL Serverに接続するためにパッケージをインストールします。
下記のコマンドをターミナルを使ってインストールしていきます。
dotnet add package System.Data.SqlClient
接続文字列の設定
Windows認証の接続文字列は下記のように書きます。
Server=<サーバ名>;Database=<データベース名>;Integrated Security=true
Windows 認証を使用する場合、接続文字列で Integrated Security=SSPI; を指定します。
以上がWindows認証の設定方法です。
パターン①:接続文字列をクラスにベタ打ち
では、つぎに実際にSQL Serverに接続してみましょう。
まずは、Form1.csクラスに接続文字列をベタ打ちするパターンを書いてみます。
そして取得したデータをDataGridViewで一覧に表示してみます。
テーブル情報をWindowsフォームのDataGridViewコンポーネントに表示する方法を追加します。DataGridView を使って SQL Server のデータをテーブルとして表示するためには、まずフォームに DataGridView を追加して、その後にコードを追加してデータをバインドする方法を示します。
コードを追加
DataGridView にデータを表示するには、DataGridView にリスト(List)をバインドします。今回はリストを直接 DataGridView に表示します。
- フォームに DataGridView を追加
まず、フォームに DataGridView を追加します。
デザイン画面でツールボックスから DataGridView をドラッグしてフォームに配置します。
DataGridView の名前を dataGridView に変更します。
ディレクトリ
今回は、SQL Serverから従業員情報Employeeを取得するため巡業院エンティティEmployeeEntity.csを用意します。
WindowsFormApp
├─ 依存関係
│ └─ パッケージ
│ └─ System.Data.SqlClient(4.9.0)
├─ Entity
│ └─ EmployeeEntity.cs
├─ Form1.cs
│ ├─ Form1.Designer.cs
│ └─ Form1.resx
├─ Program.cs
└─ Settings.setting
下記のようにデータベース接続文字列をベタ打ちで接続することでデータを取得することができます。
using System.Data;
using System.Data.SqlClient;
using WinFormsAppSQLServer.Entity;
namespace WinFormsAppSQLServer
{
public partial class Form1 : Form
{
string connectionString = $"Server=localhost;Database=test;Integrated Security=true;";
public Form1()
{
InitializeComponent();
}
private void DBConnectionButton_Click(object sender, EventArgs e)
{
string query = "SELECT * FROM [test].[dbo].[employee]";
List<EmployeeEntity> employeeList = new List<EmployeeEntity>();
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open(); // データベースに接続
using (SqlCommand command = new SqlCommand(query, connection))
{
using (SqlDataReader reader = command.ExecuteReader())
{
if (reader.HasRows)
{
while (reader.Read())
{
EmployeeEntity employeeEntity = new EmployeeEntity
{
EmployeeId = reader.GetInt32(0),
Department = reader.GetString(1),
Section = reader.GetString(2),
JobClass = reader.GetString(3),
Name = reader.GetString(4),
IpAddress = reader.GetString(5),
Sex = reader.GetString(6),
ipaddressalocation = reader.GetBoolean(7)
};
employeeList.Add(employeeEntity);
}
}
for (int i=0;i<employeeList.Count;i++)
{
Console.WriteLine($"{employeeList[i].EmployeeId},{employeeList[i].Department},{employeeList[i].Section},{employeeList[i].Name}");
}
}
}
}
dataGridView.DataSource = employeeList;
}
private void dataGridView_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace WinFormsAppSQLServer.Entity
{
public class EmployeeEntity
{
public int EmployeeId { get; set; }
public string? Department { get; set; }
public string? Section { get; set; }
public string? JobClass { get; set; }
public string? Name { get; set; }
public string? IpAddress { get; set; }
public string? Sex { get; set; }
public Boolean ipaddressalocation { get; set; }
}
}
パターン②:接続文字列を設定ファイル(Settings)に配置
パターン①では、欠点があります。
それは、接続文字列をクラスにベタ打ちしていることです。
これだと、クラスファイルが増えた場合やメンテナンス性にも影響が出てくるので避けたいものです。
では、どうするかというと設定ファイル(Settings.setting)に配置する方法です。
外部ファイルの中身
Settings.settingは下記のように書き、この情報を呼び出します。
| 名前 | 種類 | スコープ | 値 |
|---|---|---|---|
| ConnectionString | string | ユーザー | Server=localhost;Database=test;Integrated Security=true |
ディレクトリ
WindowsFormApp
├─ 依存関係
│ └─ パッケージ
│ └─ System.Data.SqlClient(4.9.0)
├─ Entity
│ └─ EmployeeEntity.cs
├─ Form1.cs
│ ├─ Form1.Designer.cs
│ └─ Form1.resx
├─ Program.cs
└─ Settings.setting
接続文字列を外部定義化することで変数となるので、いざ接続情報が変更になったとしても外部ファイルのみを変えればよいので回収が楽になります。
using System.Data;
using System.Data.SqlClient;
using WinFormsAppSQLServer.Entity;
namespace WinFormsAppSQLServer
{
public partial class Form1 : Form
{
string connectionString = Settings.Default.ConnectionString;
public Form1()
{
InitializeComponent();
}
private void DBConnectionButton_Click(object sender, EventArgs e)
{
string query = "SELECT * FROM [test].[dbo].[employee]";
List<EmployeeEntity> employeeList = new List<EmployeeEntity>();
using (SqlConnection connection = new SqlConnection(connectionString2))//connectionString
{
connection.Open(); // データベースに接続
using (SqlCommand command = new SqlCommand(query, connection))
{
using (SqlDataReader reader = command.ExecuteReader())
{
if (reader.HasRows)
{
while (reader.Read())
{
EmployeeEntity employeeEntity = new EmployeeEntity
{
EmployeeId = reader.GetInt32(0),
Department = reader.GetString(1),
Section = reader.GetString(2),
JobClass = reader.GetString(3),
Name = reader.GetString(4),
IpAddress = reader.GetString(5),
Sex = reader.GetString(6),
ipaddressalocation = reader.GetBoolean(7)
};
employeeList.Add(employeeEntity);
}
}
for (int i=0;i<employeeList.Count;i++)
{
Console.WriteLine($"{employeeList[i].EmployeeId},{employeeList[i].Department},{employeeList[i].Section},{employeeList[i].Name}");
}
}
}
}
dataGridView.DataSource = employeeList;
}
private void dataGridView_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
}
}
}
サイト
備忘録
# Microsoft.Data.SqlClient`パッケージを使用する場合
Microsoft.Data.SqlClientを使い続けたい場合は、次の NuGet パッケージがプロジェクトにインストールが必要
■Microsoft.Data.SqlClient
■System.Security.Principal.Windows
■System.Configuration.ConfigurationManager(接続文字列の読み込み時)