ADO.NET与ORM的比较(1):ADO.NET实现CRUD

说明:个人感觉在Java领域大型开发都离不了ORM的身影,所谓的SSH就是Spring+Struts+Hibernate,除了在学习基础知识的时候被告知可以使用JDBC操作数据库之外,大量的书籍中都是讲述使用Hibernate这个ORM工具来操作数据。在.NET中操作数据库的方式有多种,除了最直接的方式就是使用ADO.NET之外,还可以使用NHibernate这个Hibernate在.NET中的实现ORM,如果你对第三方的ORM持怀疑态度,你还可以使用来自微软的实现、根正苗红的Linq或者EntityFramework。
大部分从早期就开始使用.NET开发的程序员可能对ADO.NET有种迷恋,使用ADO.NET可以充分将我们早期的SQL知识发挥得淋漓尽致,并且出于对性能的考虑,有些人对.NET中的ORM还保持一种观望态度,包括我自己也是这种态度。不过即使在实际开发中不用,并不代表我们不能去了解和比较这些技术,任何事物的出现和消亡总有其原因的,我们可以了解它们的优点和长处。所以本人抽出了几个周末的时间分别用ADO.NET、NHibernate、Linq和EntityFramework来实现对数据库单表数据的创建、读取、更新和删除操作,也就是所谓的CRUD(C:Create/R:Read/U:Update/D:Delete)。
通过实现相同功能的比较,大家自己判断那种方式更适合自己。需要说明的是,如果在VS2008中使用EntityFramework就需要安装VS2008SP1。
在开始演示之前先准备好数据,在本系列中所使用的数据库是SQL Server2005,创建和初始化数据库数据的代码如下:
/****** 对象:    Table [dbo].[UserInfo]        脚本日期: 03/08/2010 12:20:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS ( SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N '[dbo].[UserInfo]') AND type in (N 'U'))
BEGIN
CREATE TABLE [dbo].[UserInfo](
  [UserID] [ int] IDENTITY(1,1) NOT NULL,
  [UserName] [ varchar](20) COLLATE Chinese_PRC_CI_AS NOT NULL,
  [RealName] [ nvarchar](8) COLLATE Chinese_PRC_CI_AS NOT NULL,
  [Age] [ tinyint] NOT NULL,
  [Sex] [ bit] NOT NULL,
  [Mobile] [ char](11) COLLATE Chinese_PRC_CI_AS NULL,
  [Phone] [ char](11) COLLATE Chinese_PRC_CI_AS NULL,
  [Email] [ varchar](50) COLLATE Chinese_PRC_CI_AS NOT NULL,
CONSTRAINT [PK_UserInfo] PRIMARY KEY CLUSTERED    
(
  [UserID] ASC
) WITH (IGNORE_DUP_KEY = OFF)
)
END
GO
IF NOT EXISTS ( SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID(N '[dbo].[UserInfo]') AND name = N 'IX_UserName')
CREATE UNIQUE NONCLUSTERED INDEX [IX_UserName] ON [dbo].[UserInfo]    
(
  [UserName] ASC
) WITH (IGNORE_DUP_KEY = ON)
GO
 
下面开始演示如何使用ADO.NET实现CRUD功能。
一、配置
创建一个控制台或者类库项目,并且添加一个app.config配置文件,在此文件中添加数据库配置信息,如下:
< connectionStrings >
   < add name ="Conn" connectionString ="Data Source=zhou;Initial Catalog=AspNetStudy;User ID=sa;Password=jerry" />
</ connectionStrings >
 
二、创建实体类
InBlock.gif using System;
InBlock.gif using System.Collections.Generic;
InBlock.gif using System.Text;
InBlock.gif
InBlock.gif namespace ADODoNETDemo
InBlock.gif{
InBlock.gif         public class UserInfo
InBlock.gif        {
InBlock.gif                 /// <summary>
InBlock.gif                 /// 用户编号
InBlock.gif                 /// </summary>
InBlock.gif                 public int UserId { get; set; }
InBlock.gif                 /// <summary>
InBlock.gif                 /// 用户名
InBlock.gif                 /// </summary>
InBlock.gif                 public string UserName { get; set; }
InBlock.gif                 /// <summary>
InBlock.gif                 /// 真实姓名
InBlock.gif                 /// </summary>
InBlock.gif                 public string RealName { get; set; }
InBlock.gif                 /// <summary>
InBlock.gif                 /// 年龄
InBlock.gif                 /// </summary>
InBlock.gif                 public byte Age { get; set; }
InBlock.gif                 /// <summary>
InBlock.gif                 /// 性别
InBlock.gif                 /// </summary>
InBlock.gif                 public bool Sex { get; set; }
InBlock.gif                 /// <summary>
InBlock.gif                 /// 电子邮件
InBlock.gif                 /// </summary>
InBlock.gif                 public string Email { get; set; }
InBlock.gif                 /// <summary>
InBlock.gif                 /// 手机号
InBlock.gif                 /// </summary>
InBlock.gif                 public string Mobile { get; set; }
InBlock.gif                 /// <summary>
InBlock.gif                 /// 电话
InBlock.gif                 /// </summary>
InBlock.gif                 public string Phone { get; set; }
InBlock.gif        }
InBlock.gif}
 
三、创建数据库访问通用类
说明:下面的这个数据库通用类适用于访问数据库中任意表,不管是基于文本方式SQL、参数化SQL语句或者存储过程都可以。
很郁闷受篇幅限制,这里将代码放在附件里。
四、创建CRUD类
对数据库实现增删改查功能的类的代码如下:
InBlock.gif using System;
InBlock.gif using System.Collections.Generic;
InBlock.gif using System.Linq;
InBlock.gif using System.Text;
InBlock.gif using System.Data.SqlClient;
InBlock.gif using System.Data;
InBlock.gif
InBlock.gif namespace ADODoNETDemo
InBlock.gif{
InBlock.gif         /// <summary>
InBlock.gif         /// 用ADO.NET实现CRUD功能
InBlock.gif         /// </summary>
InBlock.gif         public class ADODotNetCRUD
InBlock.gif        {
InBlock.gif                 /// <summary>
InBlock.gif                 /// 统计用户总数
InBlock.gif                 /// </summary>
InBlock.gif                 /// <returns></returns>
InBlock.gif                 public int Count()
InBlock.gif                {
InBlock.gif                         string sql = "select count(1) from UserInfo";
InBlock.gif                        SqlDbHelper db = new SqlDbHelper();
InBlock.gif                         return int.Parse(db.ExecuteScalar(sql).ToString());
InBlock.gif                }
InBlock.gif                 /// <summary>
InBlock.gif                 /// 创建用户
InBlock.gif                 /// </summary>
InBlock.gif                 /// <param name="info">用户实体</param>
InBlock.gif                 /// <returns></returns>
InBlock.gif                 public bool Create(UserInfo info)
InBlock.gif                {
InBlock.gif                         string sql = "insert UserInfo(UserName,RealName,Age,Sex,Mobile,Email,Phone)values(@UserName,@RealName,@Age,@Sex,@Mobile,@Email,@Phone)";
InBlock.gif                        SqlParameter[] paramters = new SqlParameter[]{
InBlock.gif                                 new SqlParameter( "@UserName",info.UserName),
InBlock.gif                                 new SqlParameter( "@RealName",info.RealName),
InBlock.gif                                 new SqlParameter( "@Age",info.Age),
InBlock.gif                                 new SqlParameter( "@Sex",info.Sex),
InBlock.gif                                 new SqlParameter( "@Mobile",info.Mobile),
InBlock.gif                                 new SqlParameter( "@Email",info.Email),
InBlock.gif                                 new SqlParameter( "@Phone",info.Phone),
InBlock.gif                        };
InBlock.gif                        SqlDbHelper db = new SqlDbHelper();
InBlock.gif                         return db.ExecuteNonQuery(sql, CommandType.Text, paramters) > 0;
InBlock.gif                }
InBlock.gif                 /// <summary>
InBlock.gif                 /// 读取用户信息
InBlock.gif                 /// </summary>
InBlock.gif                 /// <param name="userId">用户编号</param>
InBlock.gif                 /// <returns></returns>
InBlock.gif                 public UserInfo Read( int userId)
InBlock.gif                {
InBlock.gif                         string sql = "select * from UserInfo Where UserId="+userId;
InBlock.gif                        SqlDbHelper db = new SqlDbHelper();
InBlock.gif                        DataTable data = db.ExecuteDataTable(sql);
InBlock.gif                         if (data.Rows.Count > 0)
InBlock.gif                        {
InBlock.gif                                DataRow row = data.Rows[0];
InBlock.gif                                UserInfo info = new UserInfo()
InBlock.gif                                {
InBlock.gif                                        UserId= int.Parse(row[ "UserId"].ToString()),
InBlock.gif                                        UserName=row[ "UserName"].ToString(),
InBlock.gif                                        Age= byte.Parse(row[ "Age"].ToString()),
InBlock.gif                                        Email=row[ "Email"].ToString(),
InBlock.gif                                        Mobile=row[ "Mobile"].ToString(),
InBlock.gif                                        Phone=row[ "Phone"].ToString(),
InBlock.gif                                        RealName=row[ "RealName"].ToString(),
InBlock.gif                                        Sex= bool.Parse(row[ "Sex"].ToString())
InBlock.gif                                };
InBlock.gif                                 return info;
InBlock.gif                        }
InBlock.gif                         else
InBlock.gif                        {
InBlock.gif                                 return null;
InBlock.gif                        }
InBlock.gif                }
InBlock.gif                 /// <summary>
InBlock.gif                 /// 更新用户信息
InBlock.gif                 /// </summary>
InBlock.gif                 /// <param name="info">用户实体</param>
InBlock.gif                 /// <returns></returns>
InBlock.gif                 public bool Update(UserInfo info)
InBlock.gif                {
InBlock.gif                         string sql = "update UserInfo set UserName=@UserName,RealName=@RealName,Age=@Age,Sex=@Sex,Mobile=@Mobile,Email=@Email,Phone=@Phone where UserID=@UserID";
InBlock.gif                        SqlParameter[] paramters = new SqlParameter[]{
InBlock.gif                                 new SqlParameter( "@UserName",info.UserName),
InBlock.gif                                 new SqlParameter( "@RealName",info.RealName),
InBlock.gif                                 new SqlParameter( "@Age",info.Age),
InBlock.gif                                 new SqlParameter( "@Sex",info.Sex),
InBlock.gif                                 new SqlParameter( "@Mobile",info.Mobile),
InBlock.gif                                 new SqlParameter( "@Email",info.Email),
InBlock.gif                                 new SqlParameter( "@Phone",info.Phone),
InBlock.gif                                 new SqlParameter( "@UserID",info.UserId),
InBlock.gif                        };
InBlock.gif                        SqlDbHelper db = new SqlDbHelper();
InBlock.gif                         return db.ExecuteNonQuery(sql, CommandType.Text, paramters) > 0;
InBlock.gif                }
InBlock.gif                 /// <summary>
InBlock.gif                 /// 删除用户
InBlock.gif                 /// </summary>
InBlock.gif                 /// <param name="userId">用户编号</param>
InBlock.gif                 /// <returns></returns>
InBlock.gif                 public bool Delete( int userId)
InBlock.gif                {
InBlock.gif                         string sql = "delete from UserInfo where UserId=" + userId;
InBlock.gif                        SqlDbHelper db = new SqlDbHelper();
InBlock.gif                         return db.ExecuteNonQuery(sql) > 0;
InBlock.gif                }
InBlock.gif                 /// <summary>
InBlock.gif                 /// 获取用户表中编号最大的用户
InBlock.gif                 /// </summary>
InBlock.gif                 /// <returns></returns>
InBlock.gif                 public int GetMaxUserId()
InBlock.gif                {
InBlock.gif                         string sql = "select max(userId) from UserInfo";
InBlock.gif                        SqlDbHelper db = new SqlDbHelper();
InBlock.gif                         return int.Parse(db.ExecuteScalar(sql).ToString());
InBlock.gif                }
InBlock.gif        }
InBlock.gif}
五、NUnit单元测试代码
在进行单元测试时没有使用VS自带的单元测试工具,仍是我平常用惯了的NUnit,下面是代码:
很遗憾,受篇幅限制,这里代码也以附件形式提供。
六、点评
在使用ADO.NET操作数据库时个人觉得有如下优点,可以随心所欲地使用熟知的SQL语句甚至是存储过程,在使用统计、分组功能时感觉尤其强烈,当然前提是你的SQL基础要相当好,此外它是其它几种ORM的基础,其它几种ORM都是在底层使用ADO.NET实现与数据库的交互的,所以在效率上来说它也要高一些。它的缺点是需要自己写操作数据的语句并且需要自己编写数据库记录到实体的映射转换代码,一旦表的结构发生变动,就需要修改实体类和映射转换代码。
2010/03/08
周公
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值