码迷,mamicode.com
首页 > 数据库 > 详细

SqlHelper类的编写

时间:2017-01-24 12:37:25      阅读:219      评论:0      收藏:0      [点我收藏+]

标签:blog   param   comm   new   pen   gen   name   static   collect   

 1 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   

原文地址:http://www.cnblogs.com/xiarongjin/p/6346743.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!