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); } }}

 

上一篇:Unity安装配置Android环境
下一篇:Unity手动备份、还原SqlServer数据库

发表评论

最新留言

逛到本站,mark一下
[***.202.152.39]2025年04月12日 21时35分35秒