2012年12月16日日曜日

C# でAccessデータベースに接続(コンソールプログラム)

C# でAccessデータベースに接続してテーブルのフィールドを表示するサンプルプログラム
以下のサイトを参考にさせて頂きました。
http://www.dscripts.net/2009/01/20/connect-to-microsoft-access-mdb-database-using-csharp/

以下のサンプルではc:\mdb\stock_mdb.mdb というAccessデータベースに接続してmeigara というテーブルのフィールドを表示しています。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data.OleDb;
using System.Data;
using System.Xml.Serialization;
namespace ConsoleApplication2
{
public class Program
{
private static OleDbConnection con;
static void Main()
{
try
{
con = new OleDbConnection(
@"Provider=Microsoft.JET.OLEDB.4.0;"
+ @"data source=c:\mdb\stock_mdb.mdb;Jet OLEDB"
+":Database Password=");
con.Open(); //connection must be openned
OleDbCommand cmd = new OleDbCommand(
"SELECT * from meigara", con);
OleDbDataReader reader = cmd.ExecuteReader();
while(reader.Read()) // if can read row from database
{
Console.WriteLine(reader.GetValue(1).ToString()
+ " = " + reader.GetValue(2).ToString());
}
}
catch(Exception ex)
{
Console.WriteLine("Ex: "+ex);
}
finally
{
con.Close(); // finally closes connection
}
}
}
}
view raw gistfile1.cs hosted with ❤ by GitHub

0 件のコメント:

コメントを投稿