SQL Server Compactデータベースのテーブルのデータを表示する
SQL Server Compactデータベースのテーブルのデータを表示するメソッドを作ってみました。引数にデータソース、パスワード、テーブル名を指定し、実行するとテーブル内のデータを表示します。データベース接続にはSqlCeConnectionクラスのOpenメソッドを使用します。(閉じる場合はCloseメソッドを使用します。)また、SQL文を実行するにはSqlCeCommandクラスのCommandTextにSQL文を指定します。そして、UPDATE、INSERT、または DELETE 文などの場合はExecuteNonQueryメソッドを使用します。SELECT文はExecuteReaderメソッド使い、SqlCeDataReader型のデータを取得できます。
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Data.SqlServerCe;
static void Main(string[] args) { // 表示させるデータベース・テーブルを指定する string data_source = "dbfile3.sdf"; string password = "password123"; string table_name = "電話帳テーブル"; // テーブル表示メソッドの実行 ShowTable(data_source, password, table_name); }
// テーブル表示メソッド static void ShowTable(string data_source, string password, string table_name) { // データベース接続用文字列編集 string connection_str = "Data Source = " + data_source + "; Password ='" + password + "'"; // SELECT文編集 string str_sql_select = "SELECT * FROM " + table_name; SqlCeConnection conn = null; try { // データベースへ接続 conn = new SqlCeConnection(connection_str); conn.Open(); // SQLコマンドの指定 SqlCeCommand cmd = conn.CreateCommand(); cmd.CommandText = str_sql_select; // 結果データ読み込み SqlCeDataReader scdr = cmd.ExecuteReader(); int num = 1; // 結果データの表示 while (scdr.Read()) { Console.WriteLine(num + "件目のデータ"); for (int i = 0; i <= scdr.FieldCount - 1; i++) { Console.WriteLine(scdr.GetString(i)); } Console.WriteLine(""); num++; } scdr.Close(); cmd.Dispose(); } finally { // データベースへの接続を閉じる conn.Close(); } Console.ReadLine(); }