文章代码如下:

  1. class Program
  2. {
  3. static void Main (string[] args)
  4. {
  5. //连接数据库
  6. string connString = "server=.;database=Student;user id=sa;pwd=123456";
  7. Console.WriteLine (ADOUtils.ConnDB (connString));
  8.  
  9. //查询张三的数据
  10. SqlParameter[] parameters = new[] { new SqlParameter ("@sname", "李四"), };
  11. Task<List<StudentModel>> studentInfo = ADOUtils.SelectDBAsync<StudentModel> ("select SID,SName,SGender from StudentInfo where SName=@sname ", parameters);
  12. studentInfo.ContinueWith((result) =>
  13. {
  14. if (studentInfo != null)
  15. foreach (StudentModel studentModel in result.Result)
  16. {
  17. Console.WriteLine(studentModel);
  18. }
  19. else
  20. {
  21. Console.WriteLine("未查询到数据");
  22. }
  23. });
  24.  
  25. Thread.Sleep(4000);
  26.  
  27. //SqlParameter[] parameters1 = new[] { new SqlParameter ("@gone", 1), new SqlParameter ("@gtwo", 2), };
  28. ////将两个人的性别对换。
  29. //string sqlone = "update StudentInfo set SGender=@gone where SID=20200001";
  30. //string sqltwo = "update StudentInfo set SGender=@gtwo where SID=20200002";
  31. //ADOUtils.ExcuteForTransaction (new[] { sqlone, sqltwo }, parameters1);
  32.  
  33. }
  34. }
  35.  
  36. static class ADOUtils
  37. {
  38. private static SqlConnection connection = null;
  39.  
  40. /// <summary>
  41. /// 连接数据库
  42. /// </summary>
  43. /// <param name="connString">数据库连接字符串</param>
  44. /// <returns>是否连接成功 bool</returns>
  45. public static bool ConnDB (string connString)
  46. {
  47. try
  48. {
  49. connection = new SqlConnection (connString);
  50. connection.Open ();
  51. return true;
  52. }
  53. catch
  54. {
  55. connection = null;
  56. return false;
  57. }
  58. }
  59.  
  60. /// <summary>
  61. /// 断开连接
  62. /// </summary>
  63. public static void CloseConnect ()
  64. {
  65. connection.Close ();
  66. connection.Dispose ();
  67. }
  68.  
  69. /// <summary>
  70. /// 执行增,删,改操作
  71. /// </summary>
  72. /// <param name="sql">sal语句</param>
  73. /// <param name="parameters">参数</param>
  74. /// <returns>受影响的行数</returns>
  75. public static int ExcuteSQL (string sql, SqlParameter[] parameters)
  76. {
  77. if (connection == null)
  78. {
  79. Console.WriteLine ("数据库未连接");
  80. return 0;
  81. }
  82.  
  83. using (SqlCommand command = new SqlCommand (sql, connection))
  84. {
  85. try
  86. {
  87. if (parameters != null)
  88. {
  89. command.Parameters.AddRange (parameters);
  90. }
  91.  
  92. return command.ExecuteNonQuery ();
  93. }
  94. catch
  95. {
  96. return 0;
  97. }
  98. }
  99. }
  100.  
  101. /// <summary>
  102. /// 执行聚合函数操作
  103. /// </summary>
  104. /// <param name="sql">sql语句</param>
  105. /// <param name="parameters">参数</param>
  106. /// <returns>聚合结果,如果执行出错,返回false</returns>
  107. public static object ExcuteMethods (string sql, SqlParameter[] parameters)
  108. {
  109. if (connection == null)
  110. {
  111. Console.WriteLine ("数据库未连接");
  112. return 0;
  113. }
  114.  
  115. using (SqlCommand command = new SqlCommand (sql, connection))
  116. {
  117. try
  118. {
  119. if (parameters != null)
  120. {
  121. command.Parameters.AddRange (parameters);
  122. }
  123.  
  124. return command.ExecuteScalar ();
  125. }
  126. catch
  127. {
  128. return false;
  129. }
  130. }
  131. }
  132.  
  133. /// <summary>
  134. /// 执行查询操作(泛型版)
  135. /// </summary>
  136. /// <param name="sql">sql语句</param>
  137. /// <param name="parameters">参数</param>
  138. /// <returns>数据集合,出错返回null</returns>
  139. public static List<T> SelectDB<T> (string sql, SqlParameter[] parameters) where T : new()
  140. {
  141. if (connection == null)
  142. {
  143. Console.WriteLine ("数据库未连接");
  144. return null;
  145. }
  146.  
  147. using (SqlCommand command = new SqlCommand (sql, connection))
  148. {
  149. try
  150. {
  151. if (parameters != null)
  152. {
  153. command.Parameters.AddRange (parameters);
  154. }
  155.  
  156. SqlDataReader reader = command.ExecuteReader ();
  157. if (reader.HasRows)
  158. {
  159. List<T> data = new List<T> ();
  160. Type type = typeof (T);
  161. object o = Activator.CreateInstance (type);
  162. while (reader.Read ())
  163. {
  164. foreach (var property in type.GetProperties ())
  165. {
  166. property.SetValue (o, reader[property.Name]);
  167. }
  168. data.Add ((T)o);
  169. }
  170. reader.Close ();
  171. return data;
  172. }
  173.  
  174. return null;
  175. }
  176. catch
  177. {
  178. return null;
  179. }
  180. }
  181. }
  182.  
  183. /// <summary>
  184. /// 执行查询操作
  185. /// </summary>
  186. /// <param name="sql">sql语句</param>
  187. /// <param name="parameters">参数</param>
  188. /// <returns>数据集合,出错返回null</returns>
  189. public static List<StudentModel> SelectStudentInfo (string sql, SqlParameter[] parameters)
  190. {
  191. if (connection == null)
  192. {
  193. Console.WriteLine ("数据库未连接");
  194. return null;
  195. }
  196.  
  197. using (SqlCommand command = new SqlCommand (sql, connection))
  198. {
  199. try
  200. {
  201. if (parameters != null)
  202. {
  203. command.Parameters.AddRange (parameters);
  204. }
  205.  
  206. SqlDataReader reader = command.ExecuteReader ();
  207. if (reader.HasRows)
  208. {
  209. List<StudentModel> data = new List<StudentModel> ();
  210. while (reader.Read ())
  211. {
  212. StudentModel sm = new StudentModel ();
  213. sm.SID = reader.GetInt32 (0);
  214. sm.SName = reader.GetString (1);
  215. sm.SGender = reader.GetInt32 (2);
  216. data.Add (sm);
  217. }
  218. reader.Close ();
  219. return data;
  220. }
  221.  
  222. return null;
  223. }
  224. catch
  225. {
  226. return null;
  227. }
  228. }
  229. }
  230.  
  231. /// <summary>
  232. /// 使用事务执行多个增删改任务
  233. /// </summary>
  234. /// <param name="sqls">多个sql语句</param>
  235. /// <param name="parameters">多个sql语句共用的参数</param>
  236. /// <returns>返回受影响的总行数</returns>
  237. public static int ExcuteForTransaction (string[] sqls, SqlParameter[] parameters)
  238. {
  239. if (connection == null)
  240. {
  241. Console.WriteLine ("数据库未连接");
  242. return 0;
  243. }
  244. using (SqlCommand command = connection.CreateCommand ())
  245. {
  246. using (SqlTransaction transaction = connection.BeginTransaction ())
  247. {
  248. try
  249. {
  250. int count = 0;
  251. command.Transaction = transaction;
  252.  
  253. if (parameters != null)
  254. command.Parameters.AddRange (parameters);
  255.  
  256. foreach (string sql in sqls)
  257. {
  258. command.CommandText = sql;
  259. count += command.ExecuteNonQuery ();
  260. }
  261. transaction.Commit ();
  262. Console.WriteLine ("事务提交");
  263. return count;
  264. }
  265. catch (Exception exception)
  266. {
  267. Console.WriteLine (exception.Message);
  268. Console.WriteLine ("事务回滚");
  269. transaction.Rollback ();
  270. return 0;
  271. }
  272. }
  273. }
  274. }
  275.  
  276. /// <summary>
  277. /// 执行增,删,改操作(异步版)
  278. /// </summary>
  279. /// <param name="sql">sal语句</param>
  280. /// <param name="parameters">参数</param>
  281. /// <returns>受影响的行数</returns>
  282. public static async Task<int> ExcuteAsync (string sql, SqlParameter[] parameters)
  283. {
  284. if (connection == null)
  285. {
  286. Console.WriteLine ("数据库未连接");
  287. return 0;
  288. }
  289.  
  290. using (SqlCommand command = new SqlCommand (sql, connection))
  291. {
  292. try
  293. {
  294. if (parameters != null)
  295. {
  296. command.Parameters.AddRange (parameters);
  297. }
  298.  
  299. return await command.ExecuteNonQueryAsync ();
  300. }
  301. catch
  302. {
  303. return 0;
  304. }
  305. }
  306. }
  307.  
  308. /// <summary>
  309. /// 执行查询操作(异步泛型版)
  310. /// </summary>
  311. /// <param name="sql">sql语句</param>
  312. /// <param name="parameters">参数</param>
  313. /// <returns>数据集合,出错返回null</returns>
  314. public static async Task<List<T>> SelectDBAsync<T> (string sql, SqlParameter[] parameters) where T : new()
  315. {
  316. if (connection == null)
  317. {
  318. Console.WriteLine ("数据库未连接");
  319. return null;
  320. }
  321.  
  322. using (SqlCommand command = new SqlCommand (sql, connection))
  323. {
  324. try
  325. {
  326. if (parameters != null)
  327. {
  328. command.Parameters.AddRange (parameters);
  329. }
  330.  
  331. SqlDataReader reader = await command.ExecuteReaderAsync ();
  332. if (reader.HasRows)
  333. {
  334. List<T> data = new List<T> ();
  335. Type type = typeof (T);
  336. object o = Activator.CreateInstance (type);
  337. while (reader.Read ())
  338. {
  339. foreach (var property in type.GetProperties ())
  340. {
  341. property.SetValue (o, reader[property.Name]);
  342. }
  343. data.Add ((T)o);
  344. }
  345. reader.Close ();
  346. return data;
  347. }
  348.  
  349. return null;
  350. }
  351. catch
  352. {
  353. return null;
  354. }
  355. }
  356. }
  357.  
  358. /// <summary>
  359. /// 执行聚合函数操作(异步版)
  360. /// </summary>
  361. /// <param name="sql">sql语句</param>
  362. /// <param name="parameters">参数</param>
  363. /// <returns>聚合结果,如果执行出错,返回false</returns>
  364. public static async Task<object> ExcuteMethodsAsync (string sql, SqlParameter[] parameters)
  365. {
  366. if (connection == null)
  367. {
  368. Console.WriteLine ("数据库未连接");
  369. return 0;
  370. }
  371.  
  372. using (SqlCommand command = new SqlCommand (sql, connection))
  373. {
  374. try
  375. {
  376. if (parameters != null)
  377. {
  378. command.Parameters.AddRange (parameters);
  379. }
  380.  
  381. return await command.ExecuteScalarAsync ();
  382. }
  383. catch
  384. {
  385. return false;
  386. }
  387. }
  388. }
  389.  
  390. }
  391.  
  392. class StudentModel
  393. {
  394. public int SID { get; set; }
  395. public string SName { get; set; }
  396. public int SGender { get; set; }
  397.  
  398. public override string ToString ()
  399. {
  400. return $"SID:{SID}\tSName:{SName}\tSGender:{SGender}";
  401. }
  402. }

使用C#进行数据库增删改查ADO.NET(三)的更多相关文章

  1. 使用C#进行数据库增删改查ADO.NET(一)

    这节讲一下如何使用C#进行数据库的增删改查操作,本节以SQL Server数据库为例. .NET 平台,使用ADO.NET 作为与数据库服务器的桥梁,我们通过ADO.NET就可以使用C#语言操作数据库 ...

  2. 使用C#进行数据库增删改查ADO.NET(二)

    这节接着讲用C#进行数据库CRUD,高级部分.  事务: 事务是执行一批sql语句,如果中途失败,全部回滚,数据不会受影响,中途没有出错则会提交事务,真正对数据进行修改.C#提供了SqlTransac ...

  3. NX二次开发-NX访问SqlServer数据库(增删改查)C#版

    版本:NX9+VS2012+SqlServer2008r2 以前我写过一个NX访问MySQL数据库(增删改查)的文章https://www.cnblogs.com/nxopen2018/p/12297 ...

  4. Yii2.0高级框架数据库增删改查的一些操作(转)

    yii2.0框架是PHP开发的一个比较高效率的框架,集合了作者的大量心血,下面通过用户为例给大家详解yii2.0高级框架数据库增删改查的一些操作 --------------------------- ...

  5. 2. MongoDB基本操作 —— 用Mongo.exe操作数据库增删改查

    一.开篇 传统的关系数据库一般由数据库(database).表(table).记录(record)三个层次概念组成,MongoDB是由数据库(database).集合(collection).文档对象 ...

  6. go——beego的数据库增删改查

    一直都不理解使用go语言的时候,为什么还要自己去装beego,以为使用go便可以解决所有的问题,结果在朋友的点拨下,才意识到: go与beego的关系就好比是nodejs与thinkjs的关系,因此也 ...

  7. (转)SQLite数据库增删改查操作

    原文:http://www.cnblogs.com/linjiqin/archive/2011/05/26/2059182.html SQLite数据库增删改查操作 一.使用嵌入式关系型SQLite数 ...

  8. Yii2.0高级框架数据库增删改查的一些操作

    yii2.0框架是PHP开发的一个比较高效率的框架,集合了作者的大量心血,下面通过用户为例给大家详解yii2.0高级框架数据库增删改查的一些操作 --------------------------- ...

  9. WindowsPhone8 数据库增删改查

    今天第一次在博客园发表文章,如果有的地方写的不对,还请大家指出! 1.这就是一个简单wp8数据库增删改查 1.创建数据表Person [Table] public class Person : INo ...

随机推荐

  1. 输出质数(Java)

    输出质数 一.什么是质数 质数又称素数.一个大于1的自然数,除了1和它自身外,不能被其他自然数整除的数叫做质数,否则称为合数(规定1既不是质数也不是合数). 二.代码实现 1.输出100以内的质数 i ...

  2. MySQL语法基础

    一.通用语法 1.MySQL数据库的SQL语句不区分大小写 2.可以用/**/完成注释 3.常用数据类型 类型 描述 int 整型 double 浮点型 varchar 字符串型 date 日期类型, ...

  3. IgniteMe -高校网络信息安全运维挑战赛

    1 int __cdecl main(int argc, const char **argv, const char **envp) 2 { 3 void *v3; // eax 4 int v4; ...

  4. MongoDB数据库的使用

    MongoDB是一个基于分布式 文件存储的NoSQL数据库,适合存储JSON风格文件的形式. 三元素:数据库.集合和文档. 文档:对应着关系数据库中的行,就是一个对象,由键值对构成,是json的扩展B ...

  5. 前端 | JS 任务和微任务:promise 的回调和 setTimeout 的回调到底谁先执行?

    首先提一个小问题:运行下面这段 JS 代码后控制台的输出是什么? console.log("script start"); setTimeout(function () { con ...

  6. [Fundamental of Power Electronics]-PART I-6.变换器电路-0 序

    6 变换器电路 我们已经分析了包括buck,boost,buck-boost以及cuk电路,电压源逆变器等一系列电路的工作原理.利用这些变换器,可以执行许多不同的功能:降压,升压,极性反转以及直流交流 ...

  7. 【转载】C# get 与set的一些说明

    转载 在面向对象编程(OOP)中,是不允许外界直接对类的成员变量直接访问的,既然不能访问,那定义这些成员变量还有什么意义呢?所以C#中就要用set和get方法来访问私有成员变量,它们相当于外界访问对象 ...

  8. Sqlmap的基础用法(禁止用于非法用途,测试请自己搭建靶机)

    禁止用于非法用途,测试与学习请自己搭建靶机 sqlmap -r http.txt  #http.txt是我们抓取的http的请求包 sqlmap -r http.txt -p username  #指 ...

  9. Java【线程池、Lambda表达式】

    见pdf 等待唤醒机制 wait和notify 第二章 线程池 如果并发的线程数量很多,并且每个线程都是执行一个时间很短的任务就结束了,这样频繁创建线程就会大大降低 系统的效率,因为频繁创建线程和销毁 ...

  10. 数据结构之栈(JavaScript描述)

    栈数据结构   栈是一种遵从后进先出原则的有序集合.新添加或待删除的元素都保存在栈的同一端,称为栈顶,另一端就叫栈底.在栈内,锌元素都靠近栈顶,救援都接近栈底 类似栈的例子   栈也被用在编程语言你的 ...