C#でSQL Server に接続してSQLを実行するコードを紹介します。
事前準備:接続文字列の作成
データベースサーバーに接続するための接続文字列を準備する必要があります。SQL Server の場合、接続文字列は以下の書式になります。
Data Source=(SQL Server のホスト名またはIPアドレス);Initial Catalog=(接続先データベース名);Connect Timeout=60;Persist Security Info=True;User ID=(SQL Serverに接続するユーザーID);Password=(ユーザーのパスワード)
事前準備:データの準備
SQL Serverに"ProductsB"テーブルを作成し、下記のレコードを挿入します。
ProductsB テーブル
id | model | name | category | price |
1 | C-XM01 | モーダンチェア | チェア | 56000 |
2 | X-XD05 | ラージデスク | テーブル | 87000 |
3 | A-DA40 | ラウンドダイニングチェア | チェア | 28000 |
4 | O-XX100 | ナチュラルオフィス | チェア | 13800 |
5 | R-D400 | ラウンドダイニングテーブル | テーブル | 128000 |
6 | R7000 | ウッドキャビネット | その他 | 32000 |
7 | B-200 | リネンベッド | ベッド | 184500 |
8 | B-250 | ホワイトダブルベッド | ベッド | 324850 |
9 | W-80 | ワーキングチェア | チェア | 45000 |
10 | EG-10X | エルゴノミクスデスク | テーブル | 88500 |
実装例:複数のレコードを受け取るSQLの場合
UI
下図のUIを作成します。
フォームにButtonとTextBoxを配置します。
コード
下記のコードを記述します。
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.SqlClient;
namespace SimpleConnectExecSQLDemo
{
public partial class FormMain : Form
{
public FormMain()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
string constr = @"Data Source=192.168.0.1;Initial Catalog=iPentecSandBox;Connect Timeout=60;Persist Security Info=True;User ID=sa;Password=saPassword";
SqlConnection con = new SqlConnection(constr);
con.Open();
try {
string sqlstr = "select * from ProductsB";
SqlCommand com = new SqlCommand(sqlstr, con);
SqlDataReader sdr = com.ExecuteReader();
while (sdr.Read() == true) {
string model = (string)sdr["model"];
string name = (string)sdr["name"];
string category = (string)sdr["category"];
decimal price = (decimal)sdr["price"];
textBox1.Text += string.Format("{0} / {1} / {2} : {3:g} \r\n", model.Trim(), name.Trim(), category.Trim(), price);
}
sdr.Close();
com.Dispose();
}
finally {
con.Close();
}
}
}
}
解説
データベースへの接続文字列をSqlConnectionのコンストラクタに与えることで、SQLServerへの接続オブジェクト SqlConnection オブジェクトを作成します。
string constr = @"Data Source=192.168.0.1;Initial Catalog=iPentecSandBox;Connect Timeout=60;Persist Security Info=True;User ID=sa;Password=saPassword";
SqlConnection con = new SqlConnection(constr);
作成したSqlConnection オブジェクトのOpen()メソッドを呼び出すことでSQL Serverへの接続をします。
con.Open();
実行するSQLのコマンドオブジェクトを作成します。実行したいSQL文をSelCommandの引数に与えて、SqlCommandオブジェクトを作成します。
string sqlstr = "select * from ProductsB";
SqlCommand com = new SqlCommand(sqlstr, con);
SqlCommandオブジェクトのExecuteReader()メソッドを呼び出してSQLクエリの結果を読み出すSqlDataReader オブジェクトを取得します。SqlDataReader オブジェクトのRead()メソッドを呼び出すことで結果レコードを順に取得できます。レコードの値はSqlDataReader オブジェクトのインデクサーに列名を与えることで取得できます。レコードの終端の検出はSqlDataReader オブジェクトRead()メソッドの戻り値がFalseになった場所が最後のレコードとなります。
SqlDataReader sdr = com.ExecuteReader();
while (sdr.Read() == true) {
string model = (string)sdr["model"];
string name = (string)sdr["name"];
string category = (string)sdr["category"];
decimal price = (decimal)sdr["price"];
textBox1.Text += string.Format("{0} / {1} / {2} : {3:g} \r\n", model.Trim(), name.Trim(), category.Trim(), price);
SqlDataReaderを閉じ、SqlCommandも開放します。
sdr.Close();
com.Dispose();
SQLServerへの接続は、SQLの実行の終了時に確実に閉じる必要があるため、finally節で SqlConnection オブジェクトのClose()メソッドを呼び出して、SQL Serverへの接続を閉じます。
finally {
con.Close();
}
実行結果
プロジェクトを実行します。下図のウィンドウが表示されます。
[button1]をクリックします。ProductsB テーブルのレコード一覧がテキストボックスに表示されます。
実装例:結果を受け取らないSQLの場合
レコードの変更や追加など、結果を受け取らないSQL文を実行する場合は、結果を受け取るSqlDataReaderは不要のため、コードをシンプルにできます。
UI
先のプログラムに Buttonを一つ追加します。
コード
下記のコードを記述します。(button2のclickイベントを実装します。)
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.SqlClient;
namespace SimpleConnectExecSQLDemo
{
public partial class FormMain : Form
{
public FormMain()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
/*省略*/
}
private void button2_Click(object sender, EventArgs e)
{
string constr = @"Data Source=192.168.0.1;Initial Catalog=iPentecSandBox;Connect Timeout=60;Persist Security Info=True;User ID=sa;Password=saPassword";
SqlConnection con = new SqlConnection(constr);
con.Open();
try {
string sqlstr = "update ProductsB set price=206900 where model='B-200'";
SqlCommand com = new SqlCommand(sqlstr, con);
int lineCount = com.ExecuteNonQuery();
textBox1.Text += string.Format("{0:d} 行を変更しました\r\n", lineCount);
}
finally {
con.Close();
}
}
}
}
解説
SQL Serverとの接続部分のコードは先のクエリの場合と同じコードです。
string constr = @"Data Source=192.168.0.1;Initial Catalog=iPentecSandBox;Connect Timeout=60;Persist Security Info=True;User ID=sa;Password=saPassword";
SqlConnection con = new SqlConnection(constr);
con.Open();
SQLコマンドの実行に関する SqlCommandオブジェクトの作成も先のクエリの場合と同様です。今回はレコードの更新をするため、SQLにUPDATE文を記述しています。
string sqlstr = "update ProductsB set price=206900 where model='B-200'";
SqlCommand com = new SqlCommand(sqlstr, con);
今回は結果を受け取らないSQL文のため、SqlCommandオブジェクトのExecuteNonQuery()メソッドを呼び出します。このメソッドによりSQL文が実行されます。戻り値はSQLによって変更を受けた行数が戻ります。
SqlCommand com = new SqlCommand(sqlstr, con);
int lineCount = com.ExecuteNonQuery();
textBox1.Text += string.Format("{0:d} 行を変更しました\r\n", lineCount);
実行結果
プロジェクトを実行します。下図のウィンドウが表示されます。
[button1]をクリックし、レコードの内容を確認します。
[button2]をクリックします。Update文が実行され、レコードが変更されます。
再度[button1]をクリックします。modelが「B-200」の「リネンベッド」のpriceが"206900"に変更されていることが確認できます。
実装例:単一の値を受け取るSQLの場合
該当するレコードの個数など、単一の値の結果を受け取るSQL文を実行する場合は、ExecuteScalarが利用できるため、コードをシンプルにできます。
UI
下図のUIを作成します。先のプログラムのUIにButtonを一つ追加します。
コード
下記のコードを記述します。(button3のclickイベントを実装します。)
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.SqlClient;
namespace SimpleConnectExecSQLDemo
{
public partial class FormMain : Form
{
public FormMain()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
/*省略*/
}
private void button2_Click(object sender, EventArgs e)
{
/*省略*/
}
private void button3_Click(object sender, EventArgs e)
{
string constr = @"Data Source=192.168.0.1;Initial Catalog=iPentecSandBox;Connect Timeout=60;Persist Security Info=True;User ID=sa;Password=saPassword";
SqlConnection con = new SqlConnection(constr);
con.Open();
try {
string sqlstr = "select count(*) from ProductsB where price >= 50000";
SqlCommand com = new SqlCommand(sqlstr, con);
int RCount = (int)com.ExecuteScalar();
textBox1.Text += string.Format("{0:d} レコード", RCount);
}
finally {
con.Close();
}
}
}
}
解説
SQL Serverとの接続部分のコードは先のクエリの場合と同じコードです。
SQLコマンドの実行に関する SqlCommandオブジェクトの作成も先のクエリの場合と同様です。今回は単一の値を受け取るSQLにします。
string sqlstr = "select count(*) from ProductsB where price >= 50000";
SqlCommand com = new SqlCommand(sqlstr, con);
今回は一つの値の結果を受け取りSQL文のため、SqlCommandオブジェクトのExecuteScalar()メソッドを呼び出します。このメソッドによりSQL文が実行されます。戻り値の値はcount文のためintとなりますので、int型にキャストして受け取ります。受け取った値をテキストボックスに表示します。
int RCount = (int)com.ExecuteScalar();
textBox1.Text += string.Format("{0:d} レコード", RCount);
実行結果
プロジェクトを実行します。下図のウィンドウが表示されます。
[button3]をクリックします。priceが50000以上の該当するレコードの件数が表示されます。
このページのキーワード
- C# SQL Server SQL 実行
- C# SQL Server SQL文 実行
著者
iPentecのメインプログラマー
C#, ASP.NET の開発がメイン、少し前まではDelphiを愛用
最終更新日: 2024-05-01
作成日: 2016-07-18