C#でMySQLからデータ読み込み

Connector/Netを使ってMySQLに接続、指定テーブルをダンプするプログラムを書いてみます。
こういうテーブルを

+----+--------+-------+---------------------+
| id | name   | power | date                |
+----+--------+-------+---------------------+
|  1 | mikeda |    50 | 2009-04-18 21:18:30 |
|  2 | tama   |   100 | 2009-04-18 21:18:41 |
|  3 | tora   |   150 | 2009-04-18 21:18:49 |
+----+--------+-------+---------------------+

そのまま出力するだけのプログラムです。

>> DumpMySQL.exe 192.168.0.10 mikeda mikepass test_db test_tbl
id      name    power   date
1       mikeda  50      2009/04/18 21:18:30
2       tama    100     2009/04/18 21:18:41
3       tora    150     2009/04/18 21:18:49


まずConnector/Netをダウンロードインストールして参照を追加します。
参照設定→参照の追加→.NET→MySQL.Data


サンプルコード

using System;
using System.Collections.Generic;
using System.Text;
using MySql.Data.MySqlClient;

namespace DumpMySQL {
  class Program {
    static void Main(string[] args) {
      if (args.Length != 5) {
        usage();
        Environment.Exit(1);
      }

      string connStr = String.Format("server={0};user id={1};password={2};"
          + "database={3}; pooling=false", args);
      string tableName = args[4];

      //DB接続
      MySqlConnection conn = new MySqlConnection(connStr);
      conn.Open();

      //SQL実行
      MySqlCommand cmd = new MySqlCommand("SELECT * FROM " + tableName, conn);
      MySqlDataReader reader = cmd.ExecuteReader();

      //カラム名出力
      string[] names = new string[reader.FieldCount];
      for (int i = 0; i < reader.FieldCount; i++)
        names[i] = reader.GetName(i);
      Console.WriteLine(string.Join("\t", names));

      //テーブル出力
      while (reader.Read()) {
        string[] row = new string[reader.FieldCount];
        for (int i = 0; i < reader.FieldCount; i++)
          row[i] = reader.GetString(i);
        Console.WriteLine(string.Join("\t", row));
      }

      conn.Close();
    }

    private static void usage() {
      Console.WriteLine("Usage: DumpMySQL.exe server user password database table");
    }

  }
}


サンプルでは文字列としてフィールド値を取得するGetString()を使用していますが他にもいろいろ揃ってます。
特定の型として値を受け取るGetDouble()、GetDateTime()、…やObject型として受け取るGetValue()。これらはインデックスとして数値、カラム名のどちらも渡せます。GetValueと同じことは演算子を使ってreader[1]、reader["name"]のようにも書けます。
1行分を配列として一気に受け取るGetValues(Object
)もありますが、Object配列で受け取っても結局キャストするでしょうし、使い勝手はイマイチそうです。



今回は省略させてもらいましたが少なくともDB接続(conn.Open();)、クエリ発行(cmd.ExecuteReader();)の部分ではMySqlExceptionをcatchする必要があります。