找回密码
 会员注册
查看: 175|回复: 0

ASP.NET Core3.0(一) --编写SqlHelper通用类连接数据库

[复制链接]

250

主题

1

回帖

819

积分

管理员

积分
819
发表于 2024-2-29 08:14:44 | 显示全部楼层 |阅读模式

一、新建一个.NET Core的工程 文件

最终的项目文件

二、新建sqlHelper类

需要使用NuGet安装一下文件

  • System.Data.SqlClient
  • Microsoft.EntityFrameworkCore

以下代码较长,可以先粘贴复制,以后再仔细打磨

  1. using Microsoft.Extensions.Configuration;
  2. using Microsoft.Extensions.Options;
  3. using System;
  4. using System.Collections;
  5. using System.Collections.Generic;
  6. using System.Configuration;
  7. using System.Data;
  8. using System.Data.SqlClient;
  9. using System.IO;
  10. using System.Linq;
  11. using System.Web;
  12. namespace CORE3.Common
  13. {
  14. /// 此类为抽象类,
  15. /// 不允许实例化,在应用时直接调用即可
  16. /// </summary>
  17. public abstract class SqlHelper
  18. {
  19. //加载appsetting.json
  20. static IConfiguration configuration = new ConfigurationBuilder()
  21. .SetBasePath(Directory.GetCurrentDirectory())
  22. .AddJsonFile("appsettings.json").Build();
  23. /// <summary>
  24. /// 数据库连接字符串,配置文件在appsettings.json文件中
  25. /// </summary>
  26. private static readonly string connectionString = configuration["DBSetting:ConnectString"];
  27. private static Hashtable parmCache = Hashtable.Synchronized(new Hashtable());
  28. #region//ExecteNonQuery方法
  29. /// <summary>
  30. ///执行一个不需要返回值的SqlCommand命令,通过指定专用的连接字符串。
  31. /// 使用参数数组形式提供参数列表
  32. /// </summary>
  33. /// <param name="connectionString">一个有效的数据库连接字符串</param>
  34. /// <param name="cmdType">SqlCommand命令类型 (存储过程, T-SQL语句, 等等。)</param>
  35. /// <param name="cmdText">存储过程的名字或者 T-SQL 语句</param>
  36. /// <param name="commandParameters">以数组形式提供SqlCommand命令中用到的参数列表</param>
  37. /// <returns>返回一个数值表示此SqlCommand命令执行后影响的行数</returns>
  38. public static int ExecteNonQuery(string connectionString, CommandType cmdType, string cmdText, params SqlParameter[] commandParameters)
  39. {
  40. SqlCommand cmd = new SqlCommand();
  41. using (SqlConnection conn = new SqlConnection(connectionString))
  42. {
  43. //通过PrePareCommand方法将参数逐个加入到SqlCommand的参数集合中
  44. PrepareCommand(cmd, conn, null, cmdType, cmdText, commandParameters);
  45. int val = cmd.ExecuteNonQuery();
  46. //清空SqlCommand中的参数列表
  47. cmd.Parameters.Clear();
  48. return val;
  49. }
  50. }
  51. /// <summary>
  52. ///执行一个不需要返回值的SqlCommand命令,通过指定专用的连接字符串。
  53. /// 使用参数数组形式提供参数列表
  54. /// </summary>
  55. /// <param name="cmdType">SqlCommand命令类型 (存储过程, T-SQL语句, 等等。)</param>
  56. /// <param name="cmdText">存储过程的名字或者 T-SQL 语句</param>
  57. /// <param name="commandParameters">以数组形式提供SqlCommand命令中用到的参数列表</param>
  58. /// <returns>返回一个数值表示此SqlCommand命令执行后影响的行数</returns>
  59. public static int ExecteNonQuery(CommandType cmdType, string cmdText, params SqlParameter[] commandParameters)
  60. {
  61. return ExecteNonQuery(connectionString, cmdType, cmdText, commandParameters);
  62. }
  63. /// <summary>
  64. ///存储过程专用
  65. /// </summary>
  66. /// <param name="cmdText">存储过程的名字</param>
  67. /// <param name="commandParameters">以数组形式提供SqlCommand命令中用到的参数列表</param>
  68. /// <returns>返回一个数值表示此SqlCommand命令执行后影响的行数</returns>
  69. public static int ExecteNonQueryProducts(string cmdText, params SqlParameter[] commandParameters)
  70. {
  71. return ExecteNonQuery(CommandType.StoredProcedure, cmdText, commandParameters);
  72. }
  73. /// <summary>
  74. ///Sql语句专用
  75. /// </summary>
  76. /// <param name="cmdText">T_Sql语句</param>
  77. /// <param name="commandParameters">以数组形式提供SqlCommand命令中用到的参数列表</param>
  78. /// <returns>返回一个数值表示此SqlCommand命令执行后影响的行数</returns>
  79. public static int ExecteNonQueryText(string cmdText, params SqlParameter[] commandParameters)
  80. {
  81. return ExecteNonQuery(CommandType.Text, cmdText, commandParameters);
  82. }
  83. #endregion
  84. #region//GetTable方法
  85. /// <summary>
  86. /// 执行一条返回结果集的SqlCommand,通过一个已经存在的数据库连接
  87. /// 使用参数数组提供参数
  88. /// </summary>
  89. /// <param name="connecttionString">一个现有的数据库连接</param>
  90. /// <param name="cmdTye">SqlCommand命令类型</param>
  91. /// <param name="cmdText">存储过程的名字或者 T-SQL 语句</param>
  92. /// <param name="commandParameters">以数组形式提供SqlCommand命令中用到的参数列表</param>
  93. /// <returns>返回一个表集合(DataTableCollection)表示查询得到的数据集</returns>
  94. public static DataTableCollection GetTable(string connecttionString, CommandType cmdTye, string cmdText, SqlParameter[] commandParameters)
  95. {
  96. SqlCommand cmd = new SqlCommand();
  97. DataSet ds = new DataSet();
  98. using (SqlConnection conn = new SqlConnection(connecttionString))
  99. {
  100. PrepareCommand(cmd, conn, null, cmdTye, cmdText, commandParameters);
  101. SqlDataAdapter adapter = new SqlDataAdapter();
  102. adapter.SelectCommand = cmd;
  103. adapter.Fill(ds);
  104. }
  105. DataTableCollection table = ds.Tables;
  106. return table;
  107. }
  108. /// <summary>
  109. /// 执行一条返回结果集的SqlCommand,通过一个已经存在的数据库连接
  110. /// 使用参数数组提供参数
  111. /// </summary>
  112. /// <param name="cmdTye">SqlCommand命令类型</param>
  113. /// <param name="cmdText">存储过程的名字或者 T-SQL 语句</param>
  114. /// <param name="commandParameters">以数组形式提供SqlCommand命令中用到的参数列表</param>
  115. /// <returns>返回一个表集合(DataTableCollection)表示查询得到的数据集</returns>
  116. public static DataTableCollection GetTable(CommandType cmdTye, string cmdText, SqlParameter[] commandParameters)
  117. {
  118. return GetTable(connectionString, cmdTye, cmdText, commandParameters);
  119. }
  120. /// <summary>
  121. /// 存储过程专用
  122. /// </summary>
  123. /// <param name="cmdText">存储过程的名字或者 T-SQL 语句</param>
  124. /// <param name="commandParameters">以数组形式提供SqlCommand命令中用到的参数列表1</param>
  125. /// <returns>返回一个表集合(DataTableCollection)表示查询得到的数据集</returns>
  126. public static DataTableCollection GetTableProducts(string cmdText, SqlParameter[] commandParameters)
  127. {
  128. return GetTable(CommandType.StoredProcedure, cmdText, commandParameters);
  129. }
  130. /// <summary>
  131. /// Sql语句专用
  132. /// </summary>
  133. /// <param name="cmdText"> T-SQL 语句</param>
  134. /// <param name="commandParameters">以数组形式提供SqlCommand命令中用到的参数列表</param>
  135. /// <returns>返回一个表集合(DataTableCollection)表示查询得到的数据集</returns>
  136. public static DataTableCollection GetTableText(string cmdText, SqlParameter[] commandParameters)
  137. {
  138. return GetTable(CommandType.Text, cmdText, commandParameters);
  139. }
  140. #endregion
  141. /// <summary>
  142. /// 为执行命令准备参数
  143. /// </summary>
  144. /// <param name="cmd">SqlCommand 命令</param>
  145. /// <param name="conn">已经存在的数据库连接</param>
  146. /// <param name="trans">数据库事物处理</param>
  147. /// <param name="cmdType">SqlCommand命令类型 (存储过程, T-SQL语句, 等等。)</param>
  148. /// <param name="cmdText">Command text,T-SQL语句 例如 Select * from Products</param>
  149. /// <param name="cmdParms">返回带参数的命令</param>
  150. private static void PrepareCommand(SqlCommand cmd, SqlConnection conn, SqlTransaction trans, CommandType cmdType, string cmdText, SqlParameter[] cmdParms)
  151. {
  152. //判断数据库连接状态
  153. if (conn.State != ConnectionState.Open)
  154. conn.Open();
  155. cmd.Connection = conn;
  156. cmd.CommandText = cmdText;
  157. //判断是否需要事物处理
  158. if (trans != null)
  159. cmd.Transaction = trans;
  160. cmd.CommandType = cmdType;
  161. if (cmdParms != null)
  162. {
  163. foreach (SqlParameter parm in cmdParms)
  164. cmd.Parameters.Add(parm);
  165. }
  166. }
  167. /// <summary>
  168. /// Execute a SqlCommand that returns a resultset against the database specified in the connection string
  169. /// using the provided parameters.
  170. /// </summary>
  171. /// <param name="connectionString">一个有效的数据库连接字符串</param>
  172. /// <param name="cmdType">SqlCommand命令类型 (存储过程, T-SQL语句, 等等。)</param>
  173. /// <param name="cmdText">存储过程的名字或者 T-SQL 语句</param>
  174. /// <param name="commandParameters">以数组形式提供SqlCommand命令中用到的参数列表</param>
  175. /// <returns>A SqlDataReader containing the results</returns>
  176. public static SqlDataReader ExecuteReader(string connectionString, CommandType cmdType, string cmdText, params SqlParameter[] commandParameters)
  177. {
  178. SqlCommand cmd = new SqlCommand();
  179. SqlConnection conn = new SqlConnection(connectionString);
  180. // we use a try/catch here because if the method throws an exception we want to
  181. // close the connection throw code, because no datareader will exist, hence the
  182. // commandBehaviour.CloseConnection will not work
  183. try
  184. {
  185. PrepareCommand(cmd, conn, null, cmdType, cmdText, commandParameters);
  186. SqlDataReader rdr = cmd.ExecuteReader(CommandBehavior.CloseConnection);
  187. cmd.Parameters.Clear();
  188. return rdr;
  189. }
  190. catch
  191. {
  192. conn.Close();
  193. throw;
  194. }
  195. }
  196. #region//ExecuteDataSet方法
  197. /// <summary>
  198. /// return a dataset
  199. /// </summary>
  200. /// <param name="connectionString">一个有效的数据库连接字符串</param>
  201. /// <param name="cmdType">SqlCommand命令类型 (存储过程, T-SQL语句, 等等。)</param>
  202. /// <param name="cmdText">存储过程的名字或者 T-SQL 语句</param>
  203. /// <param name="commandParameters">以数组形式提供SqlCommand命令中用到的参数列表</param>
  204. /// <returns>return a dataset</returns>
  205. public static DataSet ExecuteDataSet(string connectionString, CommandType cmdType, string cmdText, params SqlParameter[] commandParameters)
  206. {
  207. SqlConnection conn = new SqlConnection(connectionString);
  208. SqlCommand cmd = new SqlCommand();
  209. try
  210. {
  211. PrepareCommand(cmd, conn, null, cmdType, cmdText, commandParameters);
  212. SqlDataAdapter da = new SqlDataAdapter();
  213. DataSet ds = new DataSet();
  214. da.SelectCommand = cmd;
  215. da.Fill(ds);
  216. return ds;
  217. }
  218. catch
  219. {
  220. conn.Close();
  221. throw;
  222. }
  223. }
  224. /// <summary>
  225. /// 返回一个DataSet
  226. /// </summary>
  227. /// <param name="cmdType">SqlCommand命令类型 (存储过程, T-SQL语句, 等等。)</param>
  228. /// <param name="cmdText">存储过程的名字或者 T-SQL 语句</param>
  229. /// <param name="commandParameters">以数组形式提供SqlCommand命令中用到的参数列表</param>
  230. /// <returns>return a dataset</returns>
  231. public static DataSet ExecuteDataSet(CommandType cmdType, string cmdText, params SqlParameter[] commandParameters)
  232. {
  233. return ExecuteDataSet(connectionString, cmdType, cmdText, commandParameters);
  234. }
  235. /// <summary>
  236. /// 返回一个DataSet
  237. /// </summary>
  238. /// <param name="cmdText">存储过程的名字</param>
  239. /// <param name="commandParameters">以数组形式提供SqlCommand命令中用到的参数列表</param>
  240. /// <returns>return a dataset</returns>
  241. public static DataSet ExecuteDataSetProducts(string cmdText, params SqlParameter[] commandParameters)
  242. {
  243. return ExecuteDataSet(connectionString, CommandType.StoredProcedure, cmdText, commandParameters);
  244. }
  245. /// <summary>
  246. /// 返回一个DataSet
  247. /// </summary>
  248. /// <param name="cmdText">T-SQL 语句</param>
  249. /// <param name="commandParameters">以数组形式提供SqlCommand命令中用到的参数列表</param>
  250. /// <returns>return a dataset</returns>
  251. public static DataSet ExecuteDataSetText(string cmdText, params SqlParameter[] commandParameters)
  252. {
  253. return ExecuteDataSet(connectionString, CommandType.Text, cmdText, commandParameters);
  254. }
  255. public static DataView ExecuteDataSet(string connectionString, string sortExpression, string direction, CommandType cmdType, string cmdText, params SqlParameter[] commandParameters)
  256. {
  257. SqlConnection conn = new SqlConnection(connectionString);
  258. SqlCommand cmd = new SqlCommand();
  259. try
  260. {
  261. PrepareCommand(cmd, conn, null, cmdType, cmdText, commandParameters);
  262. SqlDataAdapter da = new SqlDataAdapter();
  263. DataSet ds = new DataSet();
  264. da.SelectCommand = cmd;
  265. da.Fill(ds);
  266. DataView dv = ds.Tables[0].DefaultView;
  267. dv.Sort = sortExpression + " " + direction;
  268. return dv;
  269. }
  270. catch
  271. {
  272. conn.Close();
  273. throw;
  274. }
  275. }
  276. #endregion
  277. #region // ExecuteScalar方法
  278. /// <summary>
  279. /// 返回第一行的第一列
  280. /// </summary>
  281. /// <param name="cmdType">SqlCommand命令类型 (存储过程, T-SQL语句, 等等。)</param>
  282. /// <param name="cmdText">存储过程的名字或者 T-SQL 语句</param>
  283. /// <param name="commandParameters">以数组形式提供SqlCommand命令中用到的参数列表</param>
  284. /// <returns>返回一个对象</returns>
  285. public static object ExecuteScalar(CommandType cmdType, string cmdText, params SqlParameter[] commandParameters)
  286. {
  287. return ExecuteScalar(SqlHelper.connectionString, cmdType, cmdText, commandParameters);
  288. }
  289. /// <summary>
  290. /// 返回第一行的第一列存储过程专用
  291. /// </summary>
  292. /// <param name="cmdText">存储过程的名字</param>
  293. /// <param name="commandParameters">以数组形式提供SqlCommand命令中用到的参数列表</param>
  294. /// <returns>返回一个对象</returns>
  295. public static object ExecuteScalarProducts(string cmdText, params SqlParameter[] commandParameters)
  296. {
  297. return ExecuteScalar(SqlHelper.connectionString, CommandType.StoredProcedure, cmdText, commandParameters);
  298. }
  299. /// <summary>
  300. /// 返回第一行的第一列Sql语句专用
  301. /// </summary>
  302. /// <param name="cmdText">者 T-SQL 语句</param>
  303. /// <param name="commandParameters">以数组形式提供SqlCommand命令中用到的参数列表</param>
  304. /// <returns>返回一个对象</returns>
  305. public static object ExecuteScalarText(string cmdText, params SqlParameter[] commandParameters)
  306. {
  307. return ExecuteScalar(SqlHelper.connectionString, CommandType.Text, cmdText, commandParameters);
  308. }
  309. /// <summary>
  310. /// Execute a SqlCommand that returns the first column of the first record against the database specified in the connection string
  311. /// using the provided parameters.
  312. /// </summary>
  313. /// <remarks>
  314. /// e.g.:
  315. /// Object obj = ExecuteScalar(connString, CommandType.StoredProcedure, "PublishOrders", new SqlParameter("@prodid", 24));
  316. /// </remarks>
  317. /// <param name="connectionString">一个有效的数据库连接字符串</param>
  318. /// <param name="cmdType">SqlCommand命令类型 (存储过程, T-SQL语句, 等等。)</param>
  319. /// <param name="cmdText">存储过程的名字或者 T-SQL 语句</param>
  320. /// <param name="commandParameters">以数组形式提供SqlCommand命令中用到的参数列表</param>
  321. /// <returns>An object that should be converted to the expected type using Convert.To{Type}</returns>
  322. public static object ExecuteScalar(string connectionString, CommandType cmdType, string cmdText, params SqlParameter[] commandParameters)
  323. {
  324. SqlCommand cmd = new SqlCommand();
  325. using (SqlConnection connection = new SqlConnection(connectionString))
  326. {
  327. PrepareCommand(cmd, connection, null, cmdType, cmdText, commandParameters);
  328. object val = cmd.ExecuteScalar();
  329. cmd.Parameters.Clear();
  330. return val;
  331. }
  332. }
  333. /// <summary>
  334. /// Execute a SqlCommand that returns the first column of the first record against an existing database connection
  335. /// using the provided parameters.
  336. /// </summary>
  337. /// <remarks>
  338. /// e.g.:
  339. /// Object obj = ExecuteScalar(connString, CommandType.StoredProcedure, "PublishOrders", new SqlParameter("@prodid", 24));
  340. /// </remarks>
  341. /// <param name="connectionString">一个有效的数据库连接字符串</param>
  342. /// <param name="cmdType">SqlCommand命令类型 (存储过程, T-SQL语句, 等等。)</param>
  343. /// <param name="cmdText">存储过程的名字或者 T-SQL 语句</param>
  344. /// <param name="commandParameters">以数组形式提供SqlCommand命令中用到的参数列表</param>
  345. /// <returns>An object that should be converted to the expected type using Convert.To{Type}</returns>
  346. public static object ExecuteScalar(SqlConnection connection, CommandType cmdType, string cmdText, params SqlParameter[] commandParameters)
  347. {
  348. SqlCommand cmd = new SqlCommand();
  349. PrepareCommand(cmd, connection, null, cmdType, cmdText, commandParameters);
  350. object val = cmd.ExecuteScalar();
  351. cmd.Parameters.Clear();
  352. return val;
  353. }
  354. #endregion
  355. /// <summary>
  356. /// add parameter array to the cache将参数数组添加到缓存中
  357. /// </summary>
  358. /// <param name="cacheKey">Key to the parameter cache 参数缓存的键</param>
  359. /// <param name="cmdParms">an array of SqlParamters to be cached 被缓存的参数数组</param>
  360. public static void CacheParameters(string cacheKey, params SqlParameter[] commandParameters)
  361. {
  362. parmCache[cacheKey] = commandParameters;
  363. }
  364. /// <summary>
  365. /// Retrieve cached parameters 检索缓存参数
  366. /// </summary>
  367. /// <param name="cacheKey">key used to lookup parameters 用于查找参数的键 </param>
  368. /// <returns>Cached SqlParamters array 缓存参数数组</returns>
  369. public static SqlParameter[] GetCachedParameters(string cacheKey)
  370. {
  371. SqlParameter[] cachedParms = (SqlParameter[])parmCache[cacheKey];
  372. if (cachedParms == null)
  373. return null;
  374. SqlParameter[] clonedParms = new SqlParameter[cachedParms.Length];
  375. for (int i = 0, j = cachedParms.Length; i < j; i++)
  376. clonedParms[i] = (SqlParameter)((ICloneable)cachedParms[i]).Clone();
  377. return clonedParms;
  378. }
  379. /// <summary>
  380. /// 检查是否存在
  381. /// </summary>
  382. /// <param name="strSql">Sql语句</param>
  383. /// <returns>bool结果</returns>
  384. public static bool Exists(string strSql)
  385. {
  386. int cmdresult = Convert.ToInt32(ExecuteScalar(connectionString, CommandType.Text, strSql, null));
  387. if (cmdresult == 0)
  388. {
  389. return false;
  390. }
  391. else
  392. {
  393. return true;
  394. }
  395. }
  396. /// <summary>
  397. /// 检查是否存在
  398. /// </summary>
  399. /// <param name="strSql">Sql语句</param>
  400. /// <param name="cmdParms">参数</param>
  401. /// <returns>bool结果</returns>
  402. public static bool Exists(string strSql, params SqlParameter[] cmdParms)
  403. {
  404. int cmdresult = Convert.ToInt32(ExecuteScalar(connectionString, CommandType.Text, strSql, cmdParms));
  405. if (cmdresult == 0)
  406. {
  407. return false;
  408. }
  409. else
  410. {
  411. return true;
  412. }
  413. }
  414. }
  415. }
复制代码

三、修改配置文件appsettings.json

  1. {
  2. "Logging": {
  3. "IncludeScopes": false,
  4. "LogLevel": {
  5. "Default": "Warning"
  6. }
  7. },
  8. "DBSetting": {
  9. "ConnectString": "server=.;database=Test;uid=sa;pwd=root"
  10. },
  11. "AllowedHosts": "*"
  12. }
复制代码

四、编写业务逻辑代码

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Data;
  4. using System.Linq;
  5. using System.Threading.Tasks;
  6. using CORE3.Common;
  7. using System.Data.SqlClient;
  8. namespace CORE3.DLL
  9. {
  10. public class studentDLL
  11. {
  12. public DataTable GetData()
  13. {
  14. var sql = "select * from Student";
  15. var data = SqlHelper.GetTable(CommandType.Text, sql, new SqlParameter[] { });
  16. return data[0];
  17. }
  18. }
  19. }
复制代码

五、前台展示

打开项目自动生成的Pages文件夹里的idex.cshtml文件

index

(1)在Index.cshtml.cs文件中,编写代码:

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Data;
  4. using System.Linq;
  5. using System.Threading.Tasks;
  6. using CORE3.DLL;
  7. using Microsoft.AspNetCore.Mvc;
  8. using Microsoft.AspNetCore.Mvc.RazorPages;
  9. using Microsoft.Extensions.Logging;
  10. namespace CORE3.Pages
  11. {
  12. public class IndexModel : PageModel
  13. {
  14. private readonly ILogger<IndexModel> _logger;
  15. public IndexModel(ILogger<IndexModel> logger)
  16. {
  17. _logger = logger;
  18. }
  19. public DataTable Data;
  20. public void OnGet()
  21. {
  22. var studentDll = new studentDLL();
  23. Data = studentDll.GetData();
  24. }
  25. }
  26. }
复制代码

(2)在Index.cshtml文件中编写代码

  1. @page
  2. @model IndexModel
  3. @{
  4. ViewData["Title"] = "Home page";
  5. }
  6. @{
  7. var data = Model.Data;
  8. if (data.Rows.Count > 0)
  9. {
  10. for (int i = 0; i < data.Rows.Count; i++)
  11. {
  12. var row = data.Rows[i];
  13. @row["ID"];
  14. @row["Name"].ToString();
  15. @row["Sex"];
  16. }
  17. }
  18. }
复制代码

六、数据库文件

数据库文件

七、运行结果

运行结果


来源:https://blog.csdn.net/weixin_43803985/article/details/103927766
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!

本帖子中包含更多资源

您需要 登录 才可以下载或查看,没有账号?会员注册

×
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 会员注册

本版积分规则

QQ|手机版|心飞设计-版权所有:微度网络信息技术服务中心 ( 鲁ICP备17032091号-12 )|网站地图

GMT+8, 2024-12-27 00:02 , Processed in 0.537172 second(s), 28 queries .

Powered by Discuz! X3.5

© 2001-2024 Discuz! Team.

快速回复 返回顶部 返回列表