根据传智写的SqlHelper
时间:2021-07-01 10:21:17
帮助过:19人阅读
using System;
2 using System.Configuration;
3 using System.Data;
4 using System.Data.SqlClient;
5
6 namespace ADO连接数据库
7 {
8 public static class SqlHelper
9 {
10 //首先是连接字符串
11 private static readonly string Strcon = ConfigurationManager.ConnectionStrings[
"mssqlserver"].ConnectionString;
12
13 /// <summary>
14 /// 增删改返回单条无内容ExcuteNonQuery方法
15 /// </summary>
16 /// <param name="sql">Sql执行语句</param>
17 /// <param name="pms">传入变量</param>
18 /// <returns></returns>
19 public static int ExcuteNonQuery(
string sql,
params SqlParameter[] pms)
20 {
21 using (SqlConnection con =
new SqlConnection(Strcon))
22 {
23 using (SqlCommand cmd =
new SqlCommand(sql, con))
24 {
25 if (pms !=
null)
26 {
27 cmd.Parameters.AddRange(pms);
28 }
29 con.Open();
30 return cmd.ExecuteNonQuery();
31 }
32 }
33 }
34
35 /// <summary>
36 /// 查询返回单条数据内容ExcuteScalar方法
37 /// </summary>
38 /// <param name="sql">Sql执行语句</param>
39 /// <param name="pms">传入参数</param>
40 /// <returns></returns>
41 public static object ExcuteScalar(
string sql,
params SqlParameter[] pms)
42 {
43 using (SqlConnection con =
new SqlConnection(Strcon))
44 {
45 using (SqlCommand cmd =
new SqlCommand(sql, con))
46 {
47 if (pms !=
null)
48 {
49 cmd.Parameters.AddRange(pms);
50 }
51 con.Open();
52 return cmd.ExecuteScalar();
53 }
54 }
55 }
56 /// <summary>
57 /// 查询Reader方法
58 /// </summary>
59 /// <param name="sql">Sql执行语句</param>
60 /// <param name="pms">传入参数</param>
61 /// <returns></returns>
62 public static SqlDataReader Reader(
string sql,
params SqlParameter[] pms)
63 {
64 SqlConnection con =
new SqlConnection(Strcon);
65 using (SqlCommand cmd =
new SqlCommand(sql, con))
66 {
67 if (pms !=
null)
68 {
69 cmd.Parameters.AddRange(pms);
70 }
71 try
72 {
73 con.Open();
74 return cmd.ExecuteReader(System.Data.CommandBehavior.CloseConnection);
75 }
76 catch (Exception)
77 {
78 con.Close();
79 con.Dispose();
80 throw;
81 }
82 }
83 }
84 /// <summary>
85 /// DataTable方法
86 /// </summary>
87 /// <param name="sql">Sql执行语句</param>
88 /// <param name="pms">可变Sql参数</param>
89 /// <returns></returns>
90 public static DataTable Adapter(
string sql,
params SqlParameter[] pms)
91 {
92 DataTable dt =
new DataTable();
93 using (SqlDataAdapter adapter =
new SqlDataAdapter(sql, Strcon))
94 {
95 if (pms !=
null)
96 {
97 adapter.SelectCommand.Parameters.AddRange(pms);
98 }
99 adapter.Fill(dt);
100 }
101 return dt;
102 }
103 }
104 }
PS:需要引用一个配置文件
1 <?xml version="1.0" encoding="utf-8" ?>
2 <configuration>
3 <connectionStrings>
4 <add connectionString="Data Source=DESKTOP-B0QVA84;Catalog=MyfirstOne;Integrated Security=True" name="mssqlserver" />
5 </connectionStrings>
6 </configuration>
根据传智写的SqlHelper
标签:连接数据库 stat int des open nec 需要 source fill