【C#】Microsoft Access Driver でAccessデータベースからデータを取得
おはようございます。
昨日に引き続き?C#の話し。
未だに、Accessを使ったツールやシステムがあって、
個人的にはもうやめようよと思いながら、データを取得するサンプルをやってみました。
(今では他にも素晴らしいDBがありますからね。)
スポンサーリンク
ダウンロード

ダウンロードボタンをクリックします。
インストール
ダウンロードした「AccessDatabaseEngine.exe」または「AccessDatabaseEngine_X64.exe」を実行します。

インストールウィザード画面が表示されるので「次へ」ボタンをクリックします。

使用許諾契約同意画面が表示されるので、「同意します」にチェックをして「次へ」ボタンをクリックします。

インストール先指定画面が表示されるので、特に指定がなければそのまま「インストール」ボタンをクリックします。

インストール中。しばしお待ちを。

完了画面が表示されるので「OK」ボタンをクリックします。
プロジェクトの作成
VisualStudio2017で新しく WindowsForm プロジェクトを作成します。
今回は「SampleAccessDatabase」としました。
データベースの作成
いつもサンプルで使っている、猫のデータをサンプルで使用します。
Access Database は、Windows画面上で右クリック>「新規作成」>「Microsoft Access Database」より、手動で作成してください。
テーブル
列の定義は次の通り。
MSTKIND
- 区分コード
- 区分名
TBLCAT
- 番号
- 名前
- 性別
- 年齢
- 種別
- 好物
データ
MSTKIND
区分コード | 区分名 |
---|---|
01 | キジトラ |
02 | 長毛種(不明 |
03 | ミケ(っぽい |
04 | サビ |
09 | その他 |
TBLCAT
No | 名前 | 性別 | 年齢 | 区分コード | 好物 |
---|---|---|---|---|---|
1 | そら | ♂ | 6 | 01 | 犬の人形 |
2 | りく | ♂ | 5 | 02 | 人間 |
3 | うみ | ♀ | 4 | 03 | 高級ウェットフード |
4 | こうめ | ♀ | 2 | 04 | 横取りフード |
画面の作成

フォームにデータグリッドビューのみを配置したシンプルな画面を作成します。
プログラム
起動時にデータを取得して表示するようにします。
Form1.cs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 | usingSystem; usingSystem.Collections.Generic; usingSystem.ComponentModel; usingSystem.Data; usingSystem.Drawing; usingSystem.Linq; usingSystem.Text; usingSystem.Threading.Tasks; usingSystem.Windows.Forms; usingSystem.Data.Odbc; namespaceSampleAccessDatabase { publicpartial classForm1:Form { publicForm1() { InitializeComponent(); // DataGridViewの設定 dataGridView1.AutoGenerateColumns=false; dataGridView1.Columns.Add("No","No"); dataGridView1.Columns.Add("Name","名前"); dataGridView1.Columns.Add("Sex","性別"); dataGridView1.Columns.Add("Age","年齢"); dataGridView1.Columns.Add("KbnCd","種別"); dataGridView1.Columns.Add("Favorite","好物"); dataGridView1.Columns[0].DataPropertyName="No"; dataGridView1.Columns[1].DataPropertyName="Name"; dataGridView1.Columns[2].DataPropertyName="Sex"; dataGridView1.Columns[3].DataPropertyName="Age"; dataGridView1.Columns[4].DataPropertyName="KbnCd"; dataGridView1.Columns[5].DataPropertyName="Favorite"; dataGridView1.Columns[0].SortMode=DataGridViewColumnSortMode.Automatic; // データ取得 DataTable dt=newDataTable(); stringconnectionString=@"Driver={Microsoft Access Driver (*.mdb, *.accdb)};Dbq=D:\Sample.accdb; Uid=; Pwd =; "; using(OdbcConnection con=newOdbcConnection(connectionString)) { con.Open(); stringsql="SELECT * FROM TBLCAT"; using(OdbcCommand cmd=newOdbcCommand(sql,con)) { using(OdbcDataAdapter adapter=newOdbcDataAdapter(cmd)) { adapter.Fill(dt); } } } dataGridView1.DataSource=dt; } } } |
起動してみる

無事にデータが表示されました。
まとめ
データベースへの接続をいくつか記事に書いてきましたが、
Accessはバージョンや32bit、64bitと気を付けなければならないことが多く、
ちょっと面倒な感じです。
とはいえ、(ひと)昔前のシステムや、簡単なツールなんかでよく利用されているため
それなりに需要はあるんだろうなとは思いつつ、何かのお役に立てれば。
ではでは。
ディスカッション
コメント一覧
まだ、コメントがありません