使用 ADO.Net 构建数据访问类






1.48/5 (9投票s)
2007年8月6日
3分钟阅读

22008

229
本文介绍如何使用 .Net 基类进行数据库访问的 ADO.Net 工作原理
引言
当今大多数企业级应用程序都离不开关系型数据库管理系统。RDBMS 的选择取决于多种因素,例如需要对数据执行的分析、应用程序开发所使用的平台、表的大小以及需要存储的数据类型。
我认为 Microsoft SQL Server 与 Microsoft .Net 最兼容,并且在 .Net 框架类中得到了大量支持。尽管 .Net 支持所有主流平台,但无疑与 SQL Server 配合使用效果最佳。在本文中,我将讨论一些用于执行基本数据库操作的关键实践,以帮助您入门。
连接到数据库
很简单,.Net 框架中有许多类可用于不同的后端。System.Data 命名空间包含许多专用类,如 (System.Data.SQLClient.SQLConnection),以及通用类,如 (System.Data.OLEDB.OledbConnection)。为了给您一个概述,我将使用 OledbConnection 类,因为它可用于不同的后端。
您所要做的就是实例化该类并设置连接字符串属性,然后您就可以打开和关闭连接。要查找确切的连接字符串,您可以使用 udl“通用数据链接”文件并尝试连接到您的数据库。只需在桌面上右键单击并创建一个新的文本文件。单击“文件”>“另存为”>“abc.udl”。关闭文件并双击 udl 文件。现在,通过输入登录信息并选择您的驱动程序,然后单击“测试连接”来尝试连接到数据库。当测试成功后,单击“确定”关闭 udl,然后用文本编辑器打开该文件。在第三行您可以看到连接字符串。通常,您将按以下方式连接到数据库:
/// <summary> /// This method is used internally by other methods of GlobalDataAccess. /// </summary> /// <returns></returns> public bool ConnectToDatabase() { bool toReturn = false; try { Conn = new SqlConnection(sConnecionString); Conn.Open(); toReturn = true; } catch (Exception ex) { toReturn = false; throw new Exception(ex.Message + " Cannot Establish coinnection with SQL Server"); } return toReturn; }
指定要运行的存储过程或查询
您可以在 Command 对象中指定要执行的查询或存储过程。Command 对象的选择也取决于您使用的连接。对于 OLEDB.OledbConnection,您可以使用 OLEDB.OledbCommand 并传入查询和打开的连接实例。(对于打开的连接实例,在将其传入之前调用连接实例上的 Open 方法),这样您的命令就设置好了。大多数时候,Command 对象用于更新、插入、删除任何表中的数据,或者选择单行而不将结果显示在数据网格中,而是想填充下拉列表,因为它公开了 ExecuteReader 等方法,这些方法返回一个 DataReader(您可以使用它来迭代和处理每个结果)。
在需要检索数据集以显示在数据网格中或绑定到 Crystal Reports 的情况下,通常使用 DataAdapter,因为它提供了简单的操作,可以通过这些操作填充 DataAdapter。而不是使用 Command 对象,我们可以实例化一个 DataAdapter 对象并传入查询和打开的连接。DataAdapter 类在 OLEDB 和 SQLClient 命名空间中可用。在将查询和连接信息传入 DataAdapter 实例后,调用 DataAdapter 的 fill 方法并传入一个空数据集,该数据集将用查询结果填充,您就可以将其设置为数据网格或 Crystal Reports 以及各种其他控件的数据源了。
为 UI 控件获取 DataSet 或 Reader
/// <summary> /// The Name of the Stored Procedure and connection string should be supplied with the constructor /// </summary> /// <returns>Dataset that can be shown on datagrid or formatted with xsl</returns> public System.Data.DataSet ExecuteDataSet() { System.Data.DataSet ds = new System.Data.DataSet(); try { // Connect to the database if (!ConnectToDatabase()) throw new Exception("Cannot Connect to Database"); // if the connection is opened initialize the command object Cmd.Connection = Conn; DataAdapter = new SqlDataAdapter(Cmd); DataAdapter.SelectCommand.CommandType = System.Data.CommandType.StoredProcedure; DataAdapter.SelectCommand.CommandText = sCommandName; // execute the command and get the dataset and return it to caller DataAdapter.Fill(ds); return ds; } catch (Exception ex) { throw new Exception(ex.Message + "Cannot Execute Dataset"); ds = null; } finally { DataAdapter = null; Conn = null; } return ds; } // End Execute dataset
Using the Code
这是一个 3 步过程。
1. 实例化类并传入存储过程名称
2. 在 web.config 中设置连接字符串或根据需要修改它
3. 添加参数并调用执行方法
// specify the SP Name GlobalDataAccess getAllAlerts = new GlobalDataAccess("TestSP"); // specify the key name in web.config with connection string bool success = getAllAlerts.InitDBConnection("TestDB"); getAllAlerts.AddParameter("@StartDate", "01-01-2007"); getAllAlerts.AddParameter("@EndDate", "01-01-2015"); DataSet dsAllAlerts = getAllAlerts.ExecuteDataSet(); dgAlerts.DataSource = null; dgAlerts.DataSource = dsAllAlerts; ReportData.ReportDataSet = dsAllAlerts;