
C# 数据库访问通用类 (ADO.NET)
发布日期:2021-05-10 09:23:57
浏览次数:22
分类:精选文章
本文共 13085 字,大约阅读时间需要 43 分钟。
注意:本内容来自:
[1].[代码] SqlDbHelper.csusing System;using System.Collections.Generic;using System.Text;using System.Data;using System.Data.SqlClient;using System.Configuration; namespace ADODoNETDemo{ ////// 针对SQL Server数据库操作的通用类 /// 作者:周公 /// 日期:2009-01-08 /// Version:1.0 /// public class SqlDbHelper { private string connectionString; ////// 设置数据库连接字符串 /// public string ConnectionString { set { connectionString = value; } } ////// 构造函数 /// public SqlDbHelper() : this(ConfigurationManager.ConnectionStrings["Conn"].ConnectionString) { } ////// 构造函数 /// /// 数据库连接字符串 public SqlDbHelper(string connectionString) { this.connectionString = connectionString; } ////// 执行一个查询,并返回结果集 /// /// 要执行的查询SQL文本命令 ///返回查询结果集 public DataTable ExecuteDataTable(string sql) { return ExecuteDataTable(sql, CommandType.Text, null); } ////// 执行一个查询,并返回查询结果 /// /// 要执行的SQL语句 /// 要执行的查询语句的类型,如存储过程或者SQL文本命令 ///返回查询结果集 public DataTable ExecuteDataTable(string sql, CommandType commandType) { return ExecuteDataTable(sql, commandType, null); } ////// 执行一个查询,并返回查询结果 /// /// 要执行的SQL语句 /// 要执行的查询语句的类型,如存储过程或者SQL文本命令 /// Transact-SQL 语句或存储过程的参数数组 ///public DataTable ExecuteDataTable(string sql, CommandType commandType, SqlParameter[] parameters) { DataTable data = new DataTable();//实例化DataTable,用于装载查询结果集 using (SqlConnection connection = new SqlConnection(connectionString)) { using (SqlCommand command = new SqlCommand(sql, connection)) { command.CommandType = commandType;//设置command的CommandType为指定的CommandType //如果同时传入了参数,则添加这些参数 if (parameters != null) { foreach (SqlParameter parameter in parameters) { command.Parameters.Add(parameter); } } //通过包含查询SQL的SqlCommand实例来实例化SqlDataAdapter SqlDataAdapter adapter = new SqlDataAdapter(command); adapter.Fill(data);//填充DataTable } } return data; } /// /// /// /// 要执行的查询SQL文本命令 ///public SqlDataReader ExecuteReader(string sql) { return ExecuteReader(sql, CommandType.Text, null); } /// /// /// /// 要执行的SQL语句 /// 要执行的查询语句的类型,如存储过程或者SQL文本命令 ///public SqlDataReader ExecuteReader(string sql, CommandType commandType) { return ExecuteReader(sql, commandType, null); } /// /// /// /// 要执行的SQL语句 /// 要执行的查询语句的类型,如存储过程或者SQL文本命令 /// Transact-SQL 语句或存储过程的参数数组 ///public SqlDataReader ExecuteReader(string sql, CommandType commandType, SqlParameter[] parameters) { SqlConnection connection = new SqlConnection(connectionString); SqlCommand command = new SqlCommand(sql, connection); //如果同时传入了参数,则添加这些参数 if (parameters != null) { foreach (SqlParameter parameter in parameters) { command.Parameters.Add(parameter); } } connection.Open(); //CommandBehavior.CloseConnection参数指示关闭Reader对象时关闭与其关联的Connection对象 return command.ExecuteReader(CommandBehavior.CloseConnection); } /// /// /// /// 要执行的查询SQL文本命令 ///public Object ExecuteScalar(string sql) { return ExecuteScalar(sql, CommandType.Text, null); } /// /// /// /// 要执行的SQL语句 /// 要执行的查询语句的类型,如存储过程或者SQL文本命令 ///public Object ExecuteScalar(string sql, CommandType commandType) { return ExecuteScalar(sql, commandType, null); } /// /// /// /// 要执行的SQL语句 /// 要执行的查询语句的类型,如存储过程或者SQL文本命令 /// Transact-SQL 语句或存储过程的参数数组 ///public Object ExecuteScalar(string sql, CommandType commandType, SqlParameter[] parameters) { object result = null; using (SqlConnection connection = new SqlConnection(connectionString)) { using (SqlCommand command = new SqlCommand(sql, connection)) { command.CommandType = commandType;//设置command的CommandType为指定的CommandType //如果同时传入了参数,则添加这些参数 if (parameters != null) { foreach (SqlParameter parameter in parameters) { command.Parameters.Add(parameter); } } connection.Open();//打开数据库连接 result = command.ExecuteScalar(); } } return result;//返回查询结果的第一行第一列,忽略其它行和列 } /// /// 对数据库执行增删改操作 /// /// 要执行的查询SQL文本命令 ///public int ExecuteNonQuery(string sql) { return ExecuteNonQuery(sql, CommandType.Text, null); } /// /// 对数据库执行增删改操作 /// /// 要执行的SQL语句 /// 要执行的查询语句的类型,如存储过程或者SQL文本命令 ///public int ExecuteNonQuery(string sql, CommandType commandType) { return ExecuteNonQuery(sql, commandType, null); } /// /// 对数据库执行增删改操作 /// /// 要执行的SQL语句 /// 要执行的查询语句的类型,如存储过程或者SQL文本命令 /// Transact-SQL 语句或存储过程的参数数组 ///public int ExecuteNonQuery(string sql, CommandType commandType, SqlParameter[] parameters) { int count = 0; using (SqlConnection connection = new SqlConnection(connectionString)) { using (SqlCommand command = new SqlCommand(sql, connection)) { command.CommandType = commandType;//设置command的CommandType为指定的CommandType //如果同时传入了参数,则添加这些参数 if (parameters != null) { foreach (SqlParameter parameter in parameters) { command.Parameters.Add(parameter); } } connection.Open();//打开数据库连接 count = command.ExecuteNonQuery(); } } return count;//返回执行增删改操作之后,数据库中受影响的行数 } /// /// 返回当前连接的数据库中所有由用户创建的数据库 /// ///public DataTable GetTables() { DataTable data = null; using (SqlConnection connection = new SqlConnection(connectionString)) { connection.Open();//打开数据库连接 data = connection.GetSchema("Tables"); } return data; } }}[2].[代码] ADODotNetCRUD.cs using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Data.SqlClient;using System.Data; namespace ADODoNETDemo{ /// /// 用ADO.NET实现CRUD功能 /// public class ADODotNetCRUD { ////// 统计用户总数 /// ///public int Count() { string sql = "select count(1) from UserInfo"; SqlDbHelper db = new SqlDbHelper(); return int.Parse(db.ExecuteScalar(sql).ToString()); } /// /// 创建用户 /// /// 用户实体 ///public bool Create(UserInfo info) { string sql = "insert UserInfo(UserName,RealName,Age,Sex,Mobile,Email,Phone)values(@UserName,@RealName,@Age,@Sex,@Mobile,@Email,@Phone)"; SqlParameter[] paramters = new SqlParameter[]{ new SqlParameter("@UserName",info.UserName), new SqlParameter("@RealName",info.RealName), new SqlParameter("@Age",info.Age), new SqlParameter("@Sex",info.Sex), new SqlParameter("@Mobile",info.Mobile), new SqlParameter("@Email",info.Email), new SqlParameter("@Phone",info.Phone), }; SqlDbHelper db = new SqlDbHelper(); return db.ExecuteNonQuery(sql, CommandType.Text, paramters) > 0; } /// /// 读取用户信息 /// /// 用户编号 ///public UserInfo Read(int userId) { string sql = "select * from UserInfo Where UserId="+userId; SqlDbHelper db = new SqlDbHelper(); DataTable data = db.ExecuteDataTable(sql); if (data.Rows.Count > 0) { DataRow row = data.Rows[0]; UserInfo info = new UserInfo() { UserId=int.Parse(row["UserId"].ToString()), UserName=row["UserName"].ToString(), Age=byte.Parse(row["Age"].ToString()), Email=row["Email"].ToString(), Mobile=row["Mobile"].ToString(), Phone=row["Phone"].ToString(), RealName=row["RealName"].ToString(), Sex=bool.Parse(row["Sex"].ToString()) }; return info; } else { return null; } } /// /// 更新用户信息 /// /// 用户实体 ///public bool Update(UserInfo info) { string sql = "update UserInfo set UserName=@UserName,RealName=@RealName,Age=@Age,Sex=@Sex,Mobile=@Mobile,Email=@Email,Phone=@Phone where UserID=@UserID"; SqlParameter[] paramters = new SqlParameter[]{ new SqlParameter("@UserName",info.UserName), new SqlParameter("@RealName",info.RealName), new SqlParameter("@Age",info.Age), new SqlParameter("@Sex",info.Sex), new SqlParameter("@Mobile",info.Mobile), new SqlParameter("@Email",info.Email), new SqlParameter("@Phone",info.Phone), new SqlParameter("@UserID",info.UserId), }; SqlDbHelper db = new SqlDbHelper(); return db.ExecuteNonQuery(sql, CommandType.Text, paramters) > 0; } /// /// 删除用户 /// /// 用户编号 ///public bool Delete(int userId) { string sql = "delete from UserInfo where UserId=" + userId; SqlDbHelper db = new SqlDbHelper(); return db.ExecuteNonQuery(sql) > 0; } /// /// 获取用户表中编号最大的用户 /// ///public int GetMaxUserId() { string sql = "select max(userId) from UserInfo"; SqlDbHelper db = new SqlDbHelper(); return int.Parse(db.ExecuteScalar(sql).ToString()); } }}[3].[代码] 单元测试 ADODotNetTest.cs using System;using System.Collections.Generic;using System.Linq;using System.Text;using ADODoNETDemo;using NUnit.Framework; namespace NUnitTest{ [TestFixture] class ADODotNetTest { private ADODotNetCRUD instance = null; [SetUp] public void Initialize() { instance = new ADODotNetCRUD(); } [Test] /// /// 统计用户总数 /// ///public void Count() { Assert.Greater(instance.Count(), 0); } [Test] /// /// 创建用户 /// /// 用户实体 ///public void Create() { UserInfo info = new UserInfo() { Age = 12, Email = "zzz@ccav.com", Mobile = "13812345678", Phone = "01012345678", RealName = "测试" + DateTime.Now.Millisecond.ToString(), Sex = true, UserName = "zhoufoxcn" + DateTime.Now.Millisecond.ToString() }; instance.Create(info); } [Test] /// /// 读取用户信息 /// /// 用户编号 ///public void Read() { UserInfo info = instance.Read(1); Assert.NotNull(info); } [Test] /// /// 更新用户信息 /// /// 用户实体 ///public void Update() { UserInfo info = instance.Read(1); info.RealName = "测试" + DateTime.Now.Millisecond.ToString(); instance.Update(info); } [Test] /// /// 删除用户 /// /// 用户编号 ///public void DeleteByID() { int userId = instance.GetMaxUserId(); instance.Delete(userId); } }}
发表评论
最新留言
逛到本站,mark一下
[***.202.152.39]2025年04月12日 21时35分35秒
关于作者

喝酒易醉,品茶养心,人生如梦,品茶悟道,何以解忧?唯有杜康!
-- 愿君每日到此一游!
推荐文章
docker镜像命令
2021-05-10
docker容器命令
2021-05-10
CentOS7使用keepalive实现nginx的高可用
2021-05-10
Centos7.4下mysql5.6开启ssl
2021-05-10
oracle查看字符集后修改oracle服务端和客户端字符集的步骤
2021-05-10
Oracle闪回查询总结
2021-05-10
NAT端口复用型
2021-05-10
android中自定义标题栏左边距问题
2021-05-10
c学习-28
2021-05-10
Linux环境编程--03 文件IO
2021-05-10
使用C语言获取文件夹地址的方法收藏
2021-05-10
微盟实习
2021-05-10
HDU——3374 String Problem (最大最小表示法+循环节+kmp)
2021-05-10
文件读写(java)
2021-05-10
Markdown中Latex常见数学符号
2021-05-10
求1-n中x(0-9)的个数
2021-05-10
char与varchar的区别
2021-05-10
uni app 小程序中的引用的iconfont图标后预览不出页面的问题
2021-05-10
都说 TCP 是面向连接的,怎样才算是一个连接呢?
2021-05-10