zoukankan      html  css  js  c++  java
  • C# static Dbhelper

     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释放,之后它为空,会出现未将对象初始化

  • 相关阅读:
    python基础——反射
    python基础——模块
    python基础——异常处理、递归
    python基础——生成器与迭代器
    python基础——装饰器
    Python常见面试题
    Socket网络编程
    爬虫解析相关
    爬虫请求相关
    初识爬虫
  • 原文地址:https://www.cnblogs.com/zgrh/p/11127976.html
Copyright © 2011-2022 走看看