使用C#进行数据库增删改查ADO.NET(三)
文章代码如下:
- class Program
- {
- static void Main (string[] args)
- {
- //连接数据库
- string connString = "server=.;database=Student;user id=sa;pwd=123456";
- Console.WriteLine (ADOUtils.ConnDB (connString));
- //查询张三的数据
- SqlParameter[] parameters = new[] { new SqlParameter ("@sname", "李四"), };
- Task<List<StudentModel>> studentInfo = ADOUtils.SelectDBAsync<StudentModel> ("select SID,SName,SGender from StudentInfo where SName=@sname ", parameters);
- studentInfo.ContinueWith((result) =>
- {
- if (studentInfo != null)
- foreach (StudentModel studentModel in result.Result)
- {
- Console.WriteLine(studentModel);
- }
- else
- {
- Console.WriteLine("未查询到数据");
- }
- });
- Thread.Sleep(4000);
- //SqlParameter[] parameters1 = new[] { new SqlParameter ("@gone", 1), new SqlParameter ("@gtwo", 2), };
- ////将两个人的性别对换。
- //string sqlone = "update StudentInfo set SGender=@gone where SID=20200001";
- //string sqltwo = "update StudentInfo set SGender=@gtwo where SID=20200002";
- //ADOUtils.ExcuteForTransaction (new[] { sqlone, sqltwo }, parameters1);
- }
- }
- static class ADOUtils
- {
- private static SqlConnection connection = null;
- /// <summary>
- /// 连接数据库
- /// </summary>
- /// <param name="connString">数据库连接字符串</param>
- /// <returns>是否连接成功 bool</returns>
- public static bool ConnDB (string connString)
- {
- try
- {
- connection = new SqlConnection (connString);
- connection.Open ();
- return true;
- }
- catch
- {
- connection = null;
- return false;
- }
- }
- /// <summary>
- /// 断开连接
- /// </summary>
- public static void CloseConnect ()
- {
- connection.Close ();
- connection.Dispose ();
- }
- /// <summary>
- /// 执行增,删,改操作
- /// </summary>
- /// <param name="sql">sal语句</param>
- /// <param name="parameters">参数</param>
- /// <returns>受影响的行数</returns>
- public static int ExcuteSQL (string sql, SqlParameter[] parameters)
- {
- if (connection == null)
- {
- Console.WriteLine ("数据库未连接");
- return 0;
- }
- using (SqlCommand command = new SqlCommand (sql, connection))
- {
- try
- {
- if (parameters != null)
- {
- command.Parameters.AddRange (parameters);
- }
- return command.ExecuteNonQuery ();
- }
- catch
- {
- return 0;
- }
- }
- }
- /// <summary>
- /// 执行聚合函数操作
- /// </summary>
- /// <param name="sql">sql语句</param>
- /// <param name="parameters">参数</param>
- /// <returns>聚合结果,如果执行出错,返回false</returns>
- public static object ExcuteMethods (string sql, SqlParameter[] parameters)
- {
- if (connection == null)
- {
- Console.WriteLine ("数据库未连接");
- return 0;
- }
- using (SqlCommand command = new SqlCommand (sql, connection))
- {
- try
- {
- if (parameters != null)
- {
- command.Parameters.AddRange (parameters);
- }
- return command.ExecuteScalar ();
- }
- catch
- {
- return false;
- }
- }
- }
- /// <summary>
- /// 执行查询操作(泛型版)
- /// </summary>
- /// <param name="sql">sql语句</param>
- /// <param name="parameters">参数</param>
- /// <returns>数据集合,出错返回null</returns>
- public static List<T> SelectDB<T> (string sql, SqlParameter[] parameters) where T : new()
- {
- if (connection == null)
- {
- Console.WriteLine ("数据库未连接");
- return null;
- }
- using (SqlCommand command = new SqlCommand (sql, connection))
- {
- try
- {
- if (parameters != null)
- {
- command.Parameters.AddRange (parameters);
- }
- SqlDataReader reader = command.ExecuteReader ();
- if (reader.HasRows)
- {
- List<T> data = new List<T> ();
- Type type = typeof (T);
- object o = Activator.CreateInstance (type);
- while (reader.Read ())
- {
- foreach (var property in type.GetProperties ())
- {
- property.SetValue (o, reader[property.Name]);
- }
- data.Add ((T)o);
- }
- reader.Close ();
- return data;
- }
- return null;
- }
- catch
- {
- return null;
- }
- }
- }
- /// <summary>
- /// 执行查询操作
- /// </summary>
- /// <param name="sql">sql语句</param>
- /// <param name="parameters">参数</param>
- /// <returns>数据集合,出错返回null</returns>
- public static List<StudentModel> SelectStudentInfo (string sql, SqlParameter[] parameters)
- {
- if (connection == null)
- {
- Console.WriteLine ("数据库未连接");
- return null;
- }
- using (SqlCommand command = new SqlCommand (sql, connection))
- {
- try
- {
- if (parameters != null)
- {
- command.Parameters.AddRange (parameters);
- }
- SqlDataReader reader = command.ExecuteReader ();
- if (reader.HasRows)
- {
- List<StudentModel> data = new List<StudentModel> ();
- while (reader.Read ())
- {
- StudentModel sm = new StudentModel ();
- sm.SID = reader.GetInt32 (0);
- sm.SName = reader.GetString (1);
- sm.SGender = reader.GetInt32 (2);
- data.Add (sm);
- }
- reader.Close ();
- return data;
- }
- return null;
- }
- catch
- {
- return null;
- }
- }
- }
- /// <summary>
- /// 使用事务执行多个增删改任务
- /// </summary>
- /// <param name="sqls">多个sql语句</param>
- /// <param name="parameters">多个sql语句共用的参数</param>
- /// <returns>返回受影响的总行数</returns>
- public static int ExcuteForTransaction (string[] sqls, SqlParameter[] parameters)
- {
- if (connection == null)
- {
- Console.WriteLine ("数据库未连接");
- return 0;
- }
- using (SqlCommand command = connection.CreateCommand ())
- {
- using (SqlTransaction transaction = connection.BeginTransaction ())
- {
- try
- {
- int count = 0;
- command.Transaction = transaction;
- if (parameters != null)
- command.Parameters.AddRange (parameters);
- foreach (string sql in sqls)
- {
- command.CommandText = sql;
- count += command.ExecuteNonQuery ();
- }
- transaction.Commit ();
- Console.WriteLine ("事务提交");
- return count;
- }
- catch (Exception exception)
- {
- Console.WriteLine (exception.Message);
- Console.WriteLine ("事务回滚");
- transaction.Rollback ();
- return 0;
- }
- }
- }
- }
- /// <summary>
- /// 执行增,删,改操作(异步版)
- /// </summary>
- /// <param name="sql">sal语句</param>
- /// <param name="parameters">参数</param>
- /// <returns>受影响的行数</returns>
- public static async Task<int> ExcuteAsync (string sql, SqlParameter[] parameters)
- {
- if (connection == null)
- {
- Console.WriteLine ("数据库未连接");
- return 0;
- }
- using (SqlCommand command = new SqlCommand (sql, connection))
- {
- try
- {
- if (parameters != null)
- {
- command.Parameters.AddRange (parameters);
- }
- return await command.ExecuteNonQueryAsync ();
- }
- catch
- {
- return 0;
- }
- }
- }
- /// <summary>
- /// 执行查询操作(异步泛型版)
- /// </summary>
- /// <param name="sql">sql语句</param>
- /// <param name="parameters">参数</param>
- /// <returns>数据集合,出错返回null</returns>
- public static async Task<List<T>> SelectDBAsync<T> (string sql, SqlParameter[] parameters) where T : new()
- {
- if (connection == null)
- {
- Console.WriteLine ("数据库未连接");
- return null;
- }
- using (SqlCommand command = new SqlCommand (sql, connection))
- {
- try
- {
- if (parameters != null)
- {
- command.Parameters.AddRange (parameters);
- }
- SqlDataReader reader = await command.ExecuteReaderAsync ();
- if (reader.HasRows)
- {
- List<T> data = new List<T> ();
- Type type = typeof (T);
- object o = Activator.CreateInstance (type);
- while (reader.Read ())
- {
- foreach (var property in type.GetProperties ())
- {
- property.SetValue (o, reader[property.Name]);
- }
- data.Add ((T)o);
- }
- reader.Close ();
- return data;
- }
- return null;
- }
- catch
- {
- return null;
- }
- }
- }
- /// <summary>
- /// 执行聚合函数操作(异步版)
- /// </summary>
- /// <param name="sql">sql语句</param>
- /// <param name="parameters">参数</param>
- /// <returns>聚合结果,如果执行出错,返回false</returns>
- public static async Task<object> ExcuteMethodsAsync (string sql, SqlParameter[] parameters)
- {
- if (connection == null)
- {
- Console.WriteLine ("数据库未连接");
- return 0;
- }
- using (SqlCommand command = new SqlCommand (sql, connection))
- {
- try
- {
- if (parameters != null)
- {
- command.Parameters.AddRange (parameters);
- }
- return await command.ExecuteScalarAsync ();
- }
- catch
- {
- return false;
- }
- }
- }
- }
- class StudentModel
- {
- public int SID { get; set; }
- public string SName { get; set; }
- public int SGender { get; set; }
- public override string ToString ()
- {
- return $"SID:{SID}\tSName:{SName}\tSGender:{SGender}";
- }
- }
使用C#进行数据库增删改查ADO.NET(三)的更多相关文章
- 使用C#进行数据库增删改查ADO.NET(一)
这节讲一下如何使用C#进行数据库的增删改查操作,本节以SQL Server数据库为例. .NET 平台,使用ADO.NET 作为与数据库服务器的桥梁,我们通过ADO.NET就可以使用C#语言操作数据库 ...
- 使用C#进行数据库增删改查ADO.NET(二)
这节接着讲用C#进行数据库CRUD,高级部分. 事务: 事务是执行一批sql语句,如果中途失败,全部回滚,数据不会受影响,中途没有出错则会提交事务,真正对数据进行修改.C#提供了SqlTransac ...
- NX二次开发-NX访问SqlServer数据库(增删改查)C#版
版本:NX9+VS2012+SqlServer2008r2 以前我写过一个NX访问MySQL数据库(增删改查)的文章https://www.cnblogs.com/nxopen2018/p/12297 ...
- Yii2.0高级框架数据库增删改查的一些操作(转)
yii2.0框架是PHP开发的一个比较高效率的框架,集合了作者的大量心血,下面通过用户为例给大家详解yii2.0高级框架数据库增删改查的一些操作 --------------------------- ...
- 2. MongoDB基本操作 —— 用Mongo.exe操作数据库增删改查
一.开篇 传统的关系数据库一般由数据库(database).表(table).记录(record)三个层次概念组成,MongoDB是由数据库(database).集合(collection).文档对象 ...
- go——beego的数据库增删改查
一直都不理解使用go语言的时候,为什么还要自己去装beego,以为使用go便可以解决所有的问题,结果在朋友的点拨下,才意识到: go与beego的关系就好比是nodejs与thinkjs的关系,因此也 ...
- (转)SQLite数据库增删改查操作
原文:http://www.cnblogs.com/linjiqin/archive/2011/05/26/2059182.html SQLite数据库增删改查操作 一.使用嵌入式关系型SQLite数 ...
- Yii2.0高级框架数据库增删改查的一些操作
yii2.0框架是PHP开发的一个比较高效率的框架,集合了作者的大量心血,下面通过用户为例给大家详解yii2.0高级框架数据库增删改查的一些操作 --------------------------- ...
- WindowsPhone8 数据库增删改查
今天第一次在博客园发表文章,如果有的地方写的不对,还请大家指出! 1.这就是一个简单wp8数据库增删改查 1.创建数据表Person [Table] public class Person : INo ...
随机推荐
- 输出质数(Java)
输出质数 一.什么是质数 质数又称素数.一个大于1的自然数,除了1和它自身外,不能被其他自然数整除的数叫做质数,否则称为合数(规定1既不是质数也不是合数). 二.代码实现 1.输出100以内的质数 i ...
- MySQL语法基础
一.通用语法 1.MySQL数据库的SQL语句不区分大小写 2.可以用/**/完成注释 3.常用数据类型 类型 描述 int 整型 double 浮点型 varchar 字符串型 date 日期类型, ...
- IgniteMe -高校网络信息安全运维挑战赛
1 int __cdecl main(int argc, const char **argv, const char **envp) 2 { 3 void *v3; // eax 4 int v4; ...
- MongoDB数据库的使用
MongoDB是一个基于分布式 文件存储的NoSQL数据库,适合存储JSON风格文件的形式. 三元素:数据库.集合和文档. 文档:对应着关系数据库中的行,就是一个对象,由键值对构成,是json的扩展B ...
- 前端 | JS 任务和微任务:promise 的回调和 setTimeout 的回调到底谁先执行?
首先提一个小问题:运行下面这段 JS 代码后控制台的输出是什么? console.log("script start"); setTimeout(function () { con ...
- [Fundamental of Power Electronics]-PART I-6.变换器电路-0 序
6 变换器电路 我们已经分析了包括buck,boost,buck-boost以及cuk电路,电压源逆变器等一系列电路的工作原理.利用这些变换器,可以执行许多不同的功能:降压,升压,极性反转以及直流交流 ...
- 【转载】C# get 与set的一些说明
转载 在面向对象编程(OOP)中,是不允许外界直接对类的成员变量直接访问的,既然不能访问,那定义这些成员变量还有什么意义呢?所以C#中就要用set和get方法来访问私有成员变量,它们相当于外界访问对象 ...
- Sqlmap的基础用法(禁止用于非法用途,测试请自己搭建靶机)
禁止用于非法用途,测试与学习请自己搭建靶机 sqlmap -r http.txt #http.txt是我们抓取的http的请求包 sqlmap -r http.txt -p username #指 ...
- Java【线程池、Lambda表达式】
见pdf 等待唤醒机制 wait和notify 第二章 线程池 如果并发的线程数量很多,并且每个线程都是执行一个时间很短的任务就结束了,这样频繁创建线程就会大大降低 系统的效率,因为频繁创建线程和销毁 ...
- 数据结构之栈(JavaScript描述)
栈数据结构 栈是一种遵从后进先出原则的有序集合.新添加或待删除的元素都保存在栈的同一端,称为栈顶,另一端就叫栈底.在栈内,锌元素都靠近栈顶,救援都接近栈底 类似栈的例子 栈也被用在编程语言你的 ...