SqlHelper类的编写
时间:2021-07-01 10:21:17
帮助过:21人阅读
using System;
2 using System.Collections.Generic;
3 using System.Linq;
4 using System.Text;
5 using System.Data.SqlClient;
6 using System.Data;
7 using System.Configuration;
8
9 namespace WpfApplication1
10 {
11 public class SqlHelper
12 {
13 private static string connStr = ConfigurationManager.ConnectionStrings[
"dbConnStr"].ConnectionString;
14
15 public static int ExecuteNonQuery(
string sql,
params SqlParameter[] parameters)
16 {
17 using (SqlConnection conn =
new SqlConnection(connStr))
18 {
19 conn.Open();
20 using (SqlCommand cmd =
conn.CreateCommand())
21 {
22 cmd.CommandText =
sql;
23 //foreach (SqlParameter parm in parameters)
24 //{
25 // cmd.Parameters.Add(parm);
26 //}
27 cmd.Parameters.AddRange(parameters);
28 return cmd.ExecuteNonQuery();
29 }
30 }
31 }
32
33 public static object ExecuteScalar(
string sql,
params SqlParameter[] parameters)
34 {
35 using (SqlConnection conn =
new SqlConnection(connStr))
36 {
37 conn.Open();
38 using (SqlCommand cmd =
conn.CreateCommand())
39 {
40 cmd.CommandText =
sql;
41 cmd.Parameters.AddRange(parameters);
42 return cmd.ExecuteScalar();
43 }
44 }
45 }
46
47 /// <summary>
48 /// 只用来执行查询结果比较少的sql
49 /// </summary>
50 /// <param name="sql"></param>
51 /// <returns></returns>
52 public static DataTable ExecuteDataTable(
string sql,
params SqlParameter[] parameters)
53 {
54 DataSet dataSet =
new DataSet();
55 using (SqlConnection conn =
new SqlConnection(connStr))
56 {
57 conn.Open();
58 using (SqlCommand cmd =
conn.CreateCommand())
59 {
60 cmd.CommandText =
sql;
61 cmd.Parameters.AddRange(parameters);
62 SqlDataAdapter adapter =
new SqlDataAdapter(cmd);
63 adapter.Fill(dataSet);
64 return dataSet.Tables[
0];
65 }
66 }
67 }
68
69 }
70 }
SqlHelper类的编写
标签:blog param comm new pen gen name static collect