C# 創建MDB數據庫、並存放表格數據的案例

下面是近期學習C#連接MDB數據庫,通過路徑創建MDB數據庫,根據名字創建創建對用MDB數據庫中的表格,再通過DataTable創建一致的表並將數據放入,這是一個類,用完之後記得用Close()方法。

添加引用:

目的是//創建Catalog目錄類

ADOX.CatalogClass catalog = new ADOX.CatalogClass();

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Data.OleDb;
using System.Data.SqlClient;
using System.IO;
using System.Windows.Forms;
namespace PartOfJRSpace.DataHelper
{
 public class mdbHelper
 {
  private OleDbConnection myConn;
  protected string test1;
  /// <summary>
  /// 初始化連接數據庫
  /// </summary>
  /// <param name="address"></param>
  public mdbHelper(string address)
  {
   try
   {
    //創建一個 OleDbConnection對象
    string strCon = " Provider = Microsoft.Jet.OLEDB.4.0 ; Data Source =" + address;
    myConn = new OleDbConnection(strCon);
    myConn.Open();
   }
   catch (Exception ex)
   {
    ex.ToString();
   }
  }
  /// <summary>
  /// 關閉數據連接
  /// </summary>
  public void CloseConnection()
  {
   myConn.Close();
  }
  /// <summary>
  /// 創建一個類型和datatable一致的空表
  /// </summary>
  /// <param name="tableName"></param>
  public void CreateTable(string tableName,DataTable dt)
  {
   try
   {
    string sql = "create table " + tableName;
    string tableAttribute = "";
    //for (int i = 0; i < dt.Columns.Count; i++)
    //{
    // tableAttribute = tableAttribute + dt.Columns[i].ColumnName + " " + GetType(dt.Columns[i].DataType.ToString()) + ",";
    //}
    //sql = sql + "(Num AUTOINCREMENT," + tableAttribute + "CONSTRAINT table_PK PRIMARYKEY(Num));";
    for (int i=0;i<dt.Columns.Count;i++)
    {
     tableAttribute = tableAttribute + dt.Columns[i].ColumnName + " " + GetType(dt.Columns[i].DataType.ToString());
     if (i < dt.Columns.Count - 1)
     {
      tableAttribute = tableAttribute + ",";
     }
    }
    sql = sql + "(" + tableAttribute + ");";
    OleDbCommand cmd = new OleDbCommand(sql, myConn);
    cmd.ExecuteNonQuery();
   }
   catch(Exception ex)
   {
    throw;
   }
  }
  /// <summary>
  /// 將datatable導入對應名字的表中
  /// </summary>
  /// <param name="path"></param>
  /// <param name="name"></param>
  /// <param name="dt"></param>
  public void DatatableToMdb(string name,DataTable dt)
  {
   try
   {
    
    string strCom = string.Format("select * from {0}", name);
    OleDbDataAdapter da = new OleDbDataAdapter(strCom, myConn);
    //****
    OleDbCommandBuilder cb = new OleDbCommandBuilder(da);//這裡的CommandBuilder對象一定不要忘瞭,一般就是寫在DataAdapter定義的後面
    cb.QuotePrefix = "[";
    cb.QuoteSuffix = "]";
    DataSet midData = new DataSet();
    da.Fill(midData, name);
    foreach (DataRow dR in dt.Rows)
    {
     DataRow dr = midData.Tables[name].NewRow();
     dr.ItemArray = dR.ItemArray;//行復制
     midData.Tables[name].Rows.Add(dr);
    }
    da.Update(midData,name);
    
   }
   catch (Exception ex)
   {
    throw;
   }
  }
  /// <summary>
  /// 獲取創建mdb表格的屬性字段類型
  /// </summary>
  /// <param name="datatype"></param>
  /// <returns></returns>
  private string GetType(string datatype)
  {
   switch (datatype)//匹配類型選擇
   {
    case "System.String":
     return "TEXT(50)";
    case "System.DateTime":
     return "DateTime";
    case "System.Double":
     return "Double";
    case "System.Int32":
    case "System.Int16":
    case "System.Int64":
     return "Int";
    default:
     return "TEXT(50)";  
   }
  }
  /// <summary>
  /// 創建Access數據庫
  /// </summary>
  /// <param name="path">文件和文件路徑</param>
  /// <returns>真為創建成功,假為創建失敗或是文件已存在</returns>
  public static bool CreateAccessDatabase(string path)
  {
   //如果文件存在反回假
   if (File.Exists(path))
   {
    MessageBox.Show("文件已存在!");
    return false;
   }
   try
   {
    //如果目錄不存在,則創建目錄
    string dirName = Path.GetDirectoryName(path);
    if (!Directory.Exists(dirName))
    {
     Directory.CreateDirectory(dirName);
    }
    //創建Catalog目錄類
    ADOX.CatalogClass catalog = new ADOX.CatalogClass();
    string _connectionStr = "Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source=" + path
           + ";";
    //根據聯結字符串使用Jet數據庫引擎創建數據庫
    catalog.Create(_connectionStr);
    catalog = null;
    return true;
   }
   catch (Exception)
   {
    throw new Exception("數據庫創建失敗!");
   }
  }
 }
 
}

補充:c#操作Access,對MDB數據的table進行操作,包括新增,讀取

文介紹C#訪問操作Access數據庫的基礎知識,並提供一個相關的例程。C#的ADO.NET還不能通過編程方式創建全新的ACCESS(MDB)數據庫,所以還隻能使用ADOX這個來自COM的鏈接庫來操作。

主要知識點如下:

using System.Data.OleDb;
using System.Data;

連接字符串:

String connectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=product.mdb";

建立連接:

OleDbConnection connection = new OleDbConnection(connectionString);

使用OleDbCommand類來執行Sql語句:

OleDbCommand cmd = new OleDbCommand(sql, connection);
connection.Open();
cmd.ExecuteNonQuery();

1.創建mdb庫,例程如下:

需要註意的是:參數mdbPath是mdb的完整路徑(不包含表的名稱)。例如:D://test.mdb

//創建mdb 
  public static bool CreateMDBDataBase(string mdbPath)
  {
   try
   {
    ADOX.CatalogClass cat = new ADOX.CatalogClass();
    cat.Create("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + mdbPath + ";");
    cat = null;
    return true;
   }
   catch { return false; }
  }

2.創建具體的表,例程如下:

通常一個mdb的可以包含n個表。下面的程序主要是創建一個table。

//新建mdb的表 
  //mdbHead是一個ArrayList,存儲的是table表中的具體列名。 
  public static bool CreateMDBTable(string mdbPath,string tableName, ArrayList mdbHead)
  {
   try
   {
    ADOX.CatalogClass cat = new ADOX.CatalogClass();
    string sAccessConnection
     = @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + mdbPath;
    ADODB.Connection cn = new ADODB.Connection();
    cn.Open(sAccessConnection, null, null, -1);
    cat.ActiveConnection = cn;
 
    //新建一個表 
    ADOX.TableClass tbl = new ADOX.TableClass();
    tbl.ParentCatalog = cat;
    tbl.Name = tableName;
 
    int size = mdbHead.Count;
    for (int i = 0; i < size; i++)
    {
     //增加一個文本字段 
     ADOX.ColumnClass col2 = new ADOX.ColumnClass();
     col2.ParentCatalog = cat;
     col2.Name = mdbHead[i].ToString();//列的名稱 
     col2.Properties["Jet OLEDB:Allow Zero Length"].Value = false;
     tbl.Columns.Append(col2, ADOX.DataTypeEnum.adVarWChar, 500);
    }
    cat.Tables.Append(tbl); //這句把表加入數據庫(非常重要) 
    tbl = null;
    cat = null;
    cn.Close();
    return true;
   }
   catch { return false; }
  }

3.讀取mdb內容(完全讀取),例程如下:

本例程返回的是一個DataTable,如需其他格式可以自行轉換。

// 讀取mdb數據 
  public static DataTable ReadAllData(string tableName, string mdbPath,ref bool success)
  {
   DataTable dt = new DataTable();
   try
   {
    DataRow dr;
    //1、建立連接 
    string strConn
     = @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + mdbPath + ";Jet OLEDB:Database Password=haoren";
    OleDbConnection odcConnection = new OleDbConnection(strConn);
    //2、打開連接 
    odcConnection.Open();
    //建立SQL查詢 
    OleDbCommand odCommand = odcConnection.CreateCommand();
    //3、輸入查詢語句 
    odCommand.CommandText = "select * from " + tableName;
    //建立讀取 
    OleDbDataReader odrReader = odCommand.ExecuteReader();
    //查詢並顯示數據 
    int size = odrReader.FieldCount;
    for (int i = 0; i < size; i++)
    {
     DataColumn dc;
     dc = new DataColumn(odrReader.GetName(i));
     dt.Columns.Add(dc);
    }
    while (odrReader.Read())
    {
     dr = dt.NewRow();
     for (int i = 0; i < size; i++)
     {
      dr[odrReader.GetName(i)] = odrReader[odrReader.GetName(i)].ToString();
     }
     dt.Rows.Add(dr);
    }
    //關閉連接 
    odrReader.Close();
    odcConnection.Close();
    success = true;
    return dt;
   }
   catch
   {
    success = false;
    return dt;
   }
  }

4.讀取mdb內容(按列讀取),例程如下:

columns數組存儲的是你要查詢的列名稱(必須確保mdb表中存在你要的列)

// 讀取mdb數據 
  public static DataTable ReadDataByColumns(string mdbPaht,string tableName, string[] columns, ref bool success)
  {
   DataTable dt = new DataTable();
   try
   {
    DataRow dr;
    //1、建立連接 
    string strConn
     = @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + mdbPath + ";Jet OLEDB:Database Password=haoren";
    OleDbConnection odcConnection = new OleDbConnection(strConn);
    //2、打開連接 
    odcConnection.Open();
    //建立SQL查詢 
    OleDbCommand odCommand = odcConnection.CreateCommand();
    //3、輸入查詢語句 
    string strColumn = "";
    for (int i = 0; i < columns.Length; i++)
    {
     strColumn += columns[i].ToString() + ",";
    }
    strColumn = strColumn.TrimEnd(',');
    odCommand.CommandText = "select "+strColumn+" from " + tableName;
    //建立讀取 
    OleDbDataReader odrReader = odCommand.ExecuteReader();
    //查詢並顯示數據 
    int size = odrReader.FieldCount;
    for (int i = 0; i < size; i++)
    {
     DataColumn dc;
     dc = new DataColumn(odrReader.GetName(i));
     dt.Columns.Add(dc);
    }
 
    while (odrReader.Read())
    {
     dr = dt.NewRow();
     for (int i = 0; i < size; i++)
     {
      dr[odrReader.GetName(i)] = odrReader[odrReader.GetName(i)].ToString();
     }
     dt.Rows.Add(dr);
    }
    //關閉連接 
    odrReader.Close();
    odcConnection.Close();
    success = true;
    return dt;
   }
   catch
   {
    success = false;
    return dt;
   }
  }

以上為個人經驗,希望能給大傢一個參考,也希望大傢多多支持WalkonNet。如有錯誤或未考慮完全的地方,望不吝賜教。

推薦閱讀: