ODBC接続を利用して SQL Server に接続してSQLを実行するコードを紹介します。
概要
ODBC接続を利用してSQL Serverに接続するには、OdbcConnectionを利用します。SQLの実行には、OdbcCommandを利用します。
事前準備
事前にODBCデータソースを作成する必要があります。ODBCデータソース作成の手順は
こちらの記事を参照してください。
プログラム
UI
下図のUIを作成します。ボタンと複数行のテキストボックスを一つずつ配置します。
コード
下記のコードを記述します。
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.Odbc;
namespace OdbcConnectionExecSqlDemo
{
public partial class FormMain : Form
{
public FormMain()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
OdbcConnection con = new OdbcConnection("Dsn=(ODBCデータソース名);id=(SQL Serverのログインユーユーザー名);Pwd=(パスワード);DataBase=(接続するデータベース名);");
con.Open();
try {
OdbcCommand oc = new OdbcCommand("select * from ProductsB",con);
OdbcDataReader odr = oc.ExecuteReader();
while (odr.Read() == true) {
textBox1.Text += "model: "+((string)odr["model"]).Trim() + "\r\n";
textBox1.Text += "name: " + ((string)odr["name"]).Trim() + "\r\n";
textBox1.Text += "category: " + ((string)odr["category"]).Trim() + "\r\n";
textBox1.Text += string.Format("Price: {0:d}\r\n", Convert.ToInt32(odr["price"]));
textBox1.Text += "----------\r\n";
}
odr.Close();
}
finally {
con.Close();
}
}
}
}
解説
動作はSqlDataConnection, SqlCommand, SqlDataReaderを利用した場合とほぼ同様です。(
参考記事)
データベースへの接続は、OdbcConnectionを利用します。OdbcConnectionのコンストラクタの引数にはデータベースを示す、ODBCデータソース名をDsnとして指定します。またデータベースへのログインに必要なユーザー情報を id, Pwd に設定します。接続後するデータベース名をDataBaseに指定します。
OdbcConnectionオブジェクトの Open()メソッドを実行し、データベースへの接続をします。
OdbcConnection con = new OdbcConnection("Dsn=(ODBCデータソース名);id=(SQL Serverのログインユーユーザー名);Pwd=(パスワード);DataBase=(接続するデータベース名);");
con.Open();
データベースの接続後に、SQLコマンドを実行します。SQLの実行はOdbcCommand オブジェクトを利用します。
OdbcCommand のコンストラクタに実行するSQL文と、OdbcConnectionを与えます。コマンドの実行は OdbcCommandクラスのExecureReaderメソッドを呼び出します。ExecureReader()の呼び出しにより、OdbcDataReaderが戻り値として取得できます。OdbcDataReaderのRead()メソッドを呼び出すことで1レコードずつ読み出せます。
レコードの値の取得は、OdbcDataReaderオブジェクトの添え字に列名を与えたインデクサー(連想配列形式)でアクセスできます。今回のプログラムでは読み取った値をテキストボックスに表示します。
OdbcCommand oc = new OdbcCommand("select * from ProductsB",con);
OdbcDataReader odr = oc.ExecuteReader();
while (odr.Read() == true) {
textBox1.Text += "model: "+((string)odr["model"]).Trim() + "\r\n";
textBox1.Text += "name: " + ((string)odr["name"]).Trim() + "\r\n";
textBox1.Text += "category: " + ((string)odr["category"]).Trim() + "\r\n";
textBox1.Text += string.Format("Price: {0:d}\r\n", Convert.ToInt32(odr["price"]));
textBox1.Text += "----------\r\n";
}
odr.Close();
データベースへの接続は確実に閉じる必要があるため、finnaly ブロック内で、OdbcConnectionオブジェクトのClose()メソッドを呼び出します。
finally {
con.Close();
}
テーブル
下記のテーブルを準備します。
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 |
実行結果
プロジェクトを実行します。下図のウィンドウが表示されます。
[button1]をクリックします。データベースにアクセスし、データベースからレコードを取得できていることが確認できます。
補足
ODBCデータソースを利用せずに接続するコードについては
こちらの記事を参照してください。
著者
iPentecのメインプログラマー
C#, ASP.NET の開発がメイン、少し前まではDelphiを愛用
最終更新日: 2024-01-07
作成日: 2017-02-20