您好,登錄后才能下訂單哦!
本篇文章為大家展示了怎么在C#項目中創建一個MDB數據庫,內容簡明扼要并且容易理解,絕對能使你眼前一亮,通過這篇文章的詳細介紹希望你能有所收獲。
添加引用:
目的是//創建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();
需要注意的是:參數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; } }
通常一個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; } }
本例程返回的是一個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; } }
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; } }
上述內容就是怎么在C#項目中創建一個MDB數據庫,你們學到知識或技能了嗎?如果還想學到更多技能或者豐富自己的知識儲備,歡迎關注億速云行業資訊頻道。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。