一个读取数据库字典的C#类
在做项目时,经常会有些字典信息保存到数据库中,在应用程序启动时需要加载到内存中,方便程序随时调用。
直接上代码:
using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Text; using System.Data.OleDb; namespace TagReceiver { class AccessHelper { string accessPath = ""; /// <summary> /// 读取LOC_OWNER表 /// </summary> /// <returns></returns> public SortedList GetCodeSet(string connectionString, string tableName) { string cmdText = String.Format("select * from {0}", tableName); SortedList sl = new SortedList(); // 创建数据库连接 OleDbConnection conn = new OleDbConnection(connectionString); // 创建command对象并保存sql查询语句 OleDbCommand cmd = new OleDbCommand(cmdText, conn); try { conn.Open(); // 创建datareader 对象来连接到表单 OleDbDataReader reader = cmd.ExecuteReader(); // 循环遍历数据库 while (reader.Read()) { sl.Add(reader.GetString(0), reader.GetString(1)); } // 关闭reader对象 reader.Close(); // 关闭连接,这很重要 conn.Close(); } // 一些通常的异常处理 catch (OleDbException e) { LogHelper lh = new LogHelper(); lh.WriteLine(".\\Logs\\DBException.log", e.Errors[0].Message); } return sl; } } }
如何调用:
SortedList slLocOwner = new SortedList(); SortedList slLocType = new SortedList(); SortedList slFreightCarFactory = new SortedList(); SortedList slPassengerCarFactory = new SortedList(); private void MainForm_Load(object sender, EventArgs e) { ... LoadDict(); ... } /// <summary> /// 加载数据库字典 /// </summary> private void LoadDict() { string connectionString = String.Format("provider=microsoft.jet.oledb.4.0;data source={0}\\Dict.mdb", Application.StartupPath); AccessHelper ah = new AccessHelper(); slLocOwner = ah.GetCodeSet(connectionString, "LOC_OWNER"); slLocType = ah.GetCodeSet(connectionString, "LOC_TYPE"); slFreightCarFactory = ah.GetCodeSet(connectionString, "CAR_FACTORY"); slPassengerCarFactory = ah.GetCodeSet(connectionString, "PASSENGERCAR_FACTORY"); }