利用Oledb操作Access mdb檔案
開啟資料庫連線:
public static OleDbConnection OpenConn(string dbFileEntity)
{
string cnstr = string.Format("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + dbFileEntity);
OleDbConnection conn = new OleDbConnection();
conn.ConnectionString = cnstr;
if (conn.State == ConnectionState.Open) conn.Close();
conn.Open();
return conn;
}
關閉資料庫連線
public static void CloseConn(OleDbConnection conn)
{
if (conn.State == ConnectionState.Open) conn.Close();
}
讀取資料表
public static DataTable Reader(string dbFileEntity, string sqlStr)
{
DataTable dt = null;
OleDbConnection conn = OpenConn(dbFileEntity);
OleDbDataAdapter da = new OleDbDataAdapter(sqlStr, conn);
DataSet ds = new DataSet();
ds.Clear();
da.Fill(ds);
dt = ds.Tables[0];
CloseConn(conn);
return dt;
}
寫入資料
public static int writeSample(string dbFileEntity)
{
const string sqlStr = @"Insert into Categories (CategoryName,Description,Picture)VALUES(@1,@2,@3)";
DataTable dt = null;
OleDbConnection conn = OpenConn(dbFileEntity);
OleDbCommand cmd = new OleDbCommand(sqlStr, conn);
cmd.Parameters.AddWithValue("@1", "Test");
cmd.Parameters.AddWithValue("@2", "Test Description");
cmd.Parameters.AddWithValue("@3", "Test Picture");
int rows = cmd.ExecuteNonQuery();
CloseConn(conn);
return rows;
}
測試程式 :
static void Main(string[] args)
{
string dbFileEntity = "Northwind.MDB";
string sqlStr = @"SELECT * from Employees";
DataTable dt = AccessController.Reader(dbFileEntity, sqlStr);
AccessController.writeSample(dbFileEntity);
//show(dt);
Console.ReadLine(); //Pause
}
private static void show(DataTable dt)
{
for (int i = 0; i < dt.Rows.Count; i++)
{
for (int j = 0; j < dt.Columns.Count; j++)
Console.Write(dt.Rows[i][j] + "\t");
Console.WriteLine();
}
}
source code at GitHub : https://github.com/Lung-Yu/C_shop/tree/master/AccessControl
文章標籤
全站熱搜
留言列表