首页 > 数据库技术 > 详细

C# static Dbhelper

时间:2019-07-03 19:31:38      阅读:88      评论:0      收藏:0      [点我收藏+]
技术分享图片
 1  public class SQLHelper {
 2         private static string connString = "";
 3         public static int Update(string sql) {
 4             SqlConnection conn = new SqlConnection(connString);
 5             SqlCommand cmd = new SqlCommand(sql, conn);
 6             try {
 7                 conn.Open();
 8                 int i = cmd.ExecuteNonQuery();
 9                 conn.Close();
10                 return i;
11             }
12             catch (Exception ex) {
13                 throw new Exception(ex.Message);
14             }
15             finally {
16                 conn.Close();
17             }
18         }
19         public static object GetSingleResult(string sql) {
20             SqlConnection conn = new SqlConnection(connString);
21             SqlCommand cmd = new SqlCommand(sql, conn);
22             try {
23                 conn.Open();
24                 object result = cmd.ExecuteScalar();
25                 conn.Close();
26                 return result;
27             }
28             catch (Exception ex) {
29                 throw ex;
30             }
31             finally {
32                 conn.Close();
33             }
34 
35         }
36         public static SqlDataReader GetReader(string sql) {
37             SqlConnection conn = new SqlConnection(connString);
38             SqlCommand cmd = new SqlCommand(sql, conn);
39             SqlDataReader objReader = null;
40             try {
41                 conn.Open();
42                 objReader = cmd.ExecuteReader(CommandBehavior.CloseConnection);
43                 return objReader;
44             }
45             catch (Exception ex) {
46                 conn.Close();
47                 throw ex;
48             }
49         }
50     }
View Code

在使用static中不可以使用Using来关闭数据库连接,因为static是静态的,只可以初始化一次,如果使用using释放,之后它为空,会出现未将对象初始化

C# static Dbhelper

原文:https://www.cnblogs.com/zgrh/p/11127976.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!