65.9K
CodeProject 正在变化。 阅读更多。
Home

Mysql数据访问层

starIconstarIconstarIcon
emptyStarIcon
starIcon
emptyStarIcon

3.57/5 (5投票s)

2009 年 4 月 20 日

CPOL

4分钟阅读

viewsIcon

43353

downloadIcon

983

这是与 mysql 数据库交互的一种简单方法。

引言

这是一种以简单的方式访问数据库并创建一些复杂查询的实现,无需事先了解 SQL 查询和 join 语句。此库支持许多功能,稍后我们将一起了解。

背景  

与数据库进行交互的方式有很多种,尤其是在最近的日子里,正如您在所有 ORM(对象关系映射)应用程序和技术中所见。有 Microsoft 提供的 Linq(语言集成查询),它仅适用于 SQL Server。NHibernate 让您无需更改代码即可随时更改数据库。还有许多其他,但这只是关于此库优势的介绍。

所以,再次重申,这不是在您的项目中使用的最佳方式。有许多更有组织的方式可以处理您的数据库并为您提供更多功能,但我提交这篇文章是为了分享想法、代码以及它的编写方式。  

优点和缺点

优点

  • 处理数据库的简单快捷方式(CRUD 操作)
  • 支持事务
  • 支持缓存
  • 易于修改
  • 易于调试,找出问题所在

缺点

  • 非强类型
  • 主设计中的一些问题

必备组件

  • Mysql 服务器 (WAMP) - 您可以 从这里 下载
  • Visual Studio 2008(任何版本,您可以使用 Express 版本)
  • Mysql .NET 连接器 - 您可以 从这里 下载

重要说明

  • 下载附加文件夹,您会找到两个项目文件夹和一个数据库脚本文件。要查看示例,请运行您的 mysql 并执行名为 Sample 的数据库下的脚本,并创建一个新用户,用户名为 sa,密码为 sa(您以后可以更改它,但这些信息已在示例项目中定义)。
  • 现在打开示例项目,检查 web config 中的应用程序设置部分,并根据需要更改连接字符串
    </appsettings>
    	<add value="server=localhost;user id=sa;password=sa;
    		database=sample" key="DatabaseConnectionString"></add>
    	<add value="true" key="CacheEnabled"></add>
    </appsettings>
  • 您会发现每个部分旁边都有一些注释,用于准确描述该函数的功能,并且在库本身内部,您会找到每个函数的完整文档。

Using the Code

为了避免重复您的代码,首先我们将在页面内创建一个函数,返回类型为 ColumnDetails,它将为我们提供有关我们正在处理的表的信息,例如我们想要的列以及我们想要从哪个控件执行任何非 select 语句,我们将获取值,这是一个示例

private ColumnsDetails CustomerClmns()
{
    ColumnsDetails clmns = new ColumnsDetails();

    //the columns inside your table 
    clmns.ColumnName.AddRange(new string[] { "CustomerId", "Name", "Description" });
    //the display name will appear when the datatable will be filled ( the alias in SQL) 
    clmns.ColumnDisplayName.AddRange(new string[] 
		{ "ID", "Customer Name", "Customer Description" });

    //use this part to make a join with other table 
    clmns.JoinDetails.Add(new JoinDetail(JoinType.LeftOutertJoinStatement, 
		"contacts", "Tel", "Telephone", "CustomerId", "CustomerId"));

    //tell the DLL I don't want to use this column in the insert statement 
    // ( it's autoincrement )
    clmns.EliminatedColumns.Add("CustomerId");

    //tell the DLL from where it will get the column values to use in 
    //all non select statements 
    clmns.ColumnValue.AddRange(new object[] { null, txtName.Text, txtDescription.Text });

    //tell the DLL when it will make any SQL statement 
    //how it will add the condition column and its value 
    clmns.ConditionColumns.Add(new ConditionColumn
	("CustomerId", ComparisonOperator.Equal, this.CustomerID, 
	TiTaN.DataAcessLayer.StatementType.Update, AndOrCondition.None));
    clmns.ConditionColumns.Add(new ConditionColumn
	("CustomerId", ComparisonOperator.Equal, this.CustomerID, 
	TiTaN.DataAcessLayer.StatementType.Delete, AndOrCondition.None));

    return clmns;
}	

一旦您在页面中创建了此函数,您就几乎完成了。接下来的步骤将是查看行以对表执行任何操作(CRUD 操作),这是一个示例。

DbManagement.SelectRecords("Customers", CustomerClmns(), 
			"CustomersCacheKey", ref app, ref cache);

让我们在转到下一行之前描述这一行。DLL 是一个 static 类(设计中的一个问题),它正在等待有关它将要处理的表的一些信息,例如我们已作为第一个参数提供的表名以及从我们刚刚创建的函数返回的列详细信息、缓存键以及对应用程序状态类和缓存类的引用(设计中的另一个问题)。

仅当您在 web.config 中启用了缓存并且将启用缓存的值设置为 true 时,才需要缓存键。您需要做的就是在 global.asax 文件中添加此键,值为 null ,如下一个示例所示,以便 DLL 在服务器首次运行时使用它来缓存传入数据,并且如果数据未更改,则每次都使用。这意味着 DLL 将从缓存的对象中获取数据,而不是从数据库中获取。

Application.Lock();
 Application.Add("CustomersCacheKey", null);
 Application.UnLock();

让我们来看一个非 select 语句,例如 insert ,看看编写它需要什么。

DbManagement.InsertNewRecord("customers", 
	CustomerClmns(), ref app, "CustomersCacheKey");

几乎与 select 语句相同,但也许有人会问,为什么在这种情况下我们将缓存键传递过去?对于任何非 select 语句,您将传递缓存键以告知 DLL 我已经更改了数据。任何请求数据的人都将从数据库中获取,而不是从缓存中获取,然后重新进行您在开始时用于缓存传入新数据的相同工作。

 try
{
DbManagement.BeginTransaction();
DbManagement.InsertNewRecord
	("customers", CustomerClmns(), ref app, "CustomersCacheKey");
//Be sure that the engine for mysql table is innodb 
throw new Exception();
DbManagement.CommitTransaction();
}
catch (Exception ex )
{
DbManagement.RollbackTransaction();
}

在此代码中,我们使用了 DLL 中的事务功能,但首先要确保您正在使用的表引擎是 InnoDB ,因为它是唯一支持事务的引擎,并且我们从 mysql 网站获取了此信息。 

其他功能与调试有关,例如在 insert 语句之后放置一个断点,您将在 DLL 中找到 2 个属性,分别用于最后执行的 SQL 语句和其中使用的参数及其值。

关注点

正如我在本文开头提到的,我发布本文仅是为了分享想法并获得反馈,以便从其他有经验的开发人员那里学习。实际上,我目前正在开发另一个库,但这次使用的是 .NET 3.0 和 3.5 附带的新接口,例如 IList IQuerable

历史

  • 2009 年 4 月 20 日:初始帖子
© . All rights reserved.