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

sqlserver数据库访问帮助类

时间:2018-04-30 18:06:23      阅读:236      评论:0      收藏:0      [点我收藏+]

标签:pwd   public   .com   scalar   .text   null   exe   nec   serve   

 

 1 /// <summary>
 2 /// 数据库访问帮助类
 3 /// </summary>
 4 public static class DbHelper
 5 {
 6 private const string ConnStr = "server=127.0.0.1;database=db_test;Uid=user1;Pwd=Ps123321;";
 7 
 8 
 9 /// <summary>
10 /// 执行 增、删、改
11 /// </summary>
12 /// <param name="sql"></param>
13 /// <param name="sqlParams"></param>
14 /// <returns></returns>
15 public static int ExecuteNonQuery(string sql, params SqlParameter[] sqlParams)
16 {
17     using (SqlConnection conn = new SqlConnection(ConnStr))
18     {
19         conn.Open();
20         using (SqlCommand comm = conn.CreateCommand())
21         {
22             comm.CommandText = sql;
23             comm.CommandType = CommandType.Text;
24             if (sqlParams != null)
25                 comm.Parameters.AddRange(sqlParams);
26             return comm.ExecuteNonQuery();
27         }
28     }
29 }
30 
31 /// <summary>
32 /// 返回1个查询结果
33 /// </summary>
34 /// <param name="sql"></param>
35 /// <param name="sqlParams"></param>
36 /// <returns></returns>
37 public static object ExecuteScalar(string sql, params SqlParameter[] sqlParams)
38 {
39     using (SqlConnection conn = new SqlConnection(ConnStr))
40     {
41         conn.Open();
42         using (SqlCommand comm = conn.CreateCommand())
43         {
44             comm.CommandText = sql;
45             comm.CommandType = CommandType.Text;
46             if (sqlParams != null)
47                 comm.Parameters.AddRange(sqlParams);
48             return comm.ExecuteScalar();
49         }
50     }
51 }
52 
53 /// <summary>
54 /// 返回查询,返回结果集
55 /// </summary>
56 /// <param name="sql"></param>
57 /// <param name="sqlParams"></param>
58 /// <returns></returns>
59 public static DataTable ExecuteQuery(string sql, params SqlParameter[] sqlParams)
60 {
61     using (SqlConnection conn = new SqlConnection(ConnStr))
62     {
63         conn.Open();
64         using (SqlCommand comm = conn.CreateCommand())
65         {
66             comm.CommandText = sql;
67             comm.CommandType = CommandType.Text;
68             if (sqlParams!=null)
69                 comm.Parameters.AddRange(sqlParams);
70             using (SqlDataAdapter adp = new SqlDataAdapter(comm))
71             {
72                 DataSet ds = new DataSet();
73                 adp.Fill(ds);
74                 return ds.Tables[0];
75             }
76         }
77     }
78 }
79 }

 

sqlserver数据库访问帮助类

标签:pwd   public   .com   scalar   .text   null   exe   nec   serve   

原文地址:https://www.cnblogs.com/glory0727/p/8973975.html

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