getcon跟数据库建立连接的方法

using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Xml.Linq;
using System.Collections.Generic;
using System.Data.SqlClient;

namespace DAL
{
    public class GetCon
    {
        private static SqlConnection conn;
        private static SqlDataAdapter da;
        private static SqlCommand com;
        private static SqlDataReader dr;
        private static string strCon;
        public GetCon()
        {

        }
        public static SqlConnection GetConnection()
        {

            strCon =ConfigurationSettings.AppSettings["zhukeConnection"].ToString();
            conn = new SqlConnection(strCon);
            return conn;
        }
        //获得SqlDataReader
        public static SqlDataReader GetReader(string sql)
        {
            SqlConnection con = GetConnection();
            com = new SqlCommand(sql, con);
            con.Open();
            dr = com.ExecuteReader();
            return dr;
        }
        //获得DataSet
        public static DataSet GetDataSet(string sql)
        {
            SqlConnection con = GetConnection();
            da = new SqlDataAdapter(sql, con);
            DataSet ds = new DataSet();
            da.Fill(ds);
            return ds;
        }
        //执行的方法
        private static void closeConnection()
        {
            if (conn.State == ConnectionState.Open)
            {
                conn.Close();
            }
            conn.Dispose();
            com.Dispose();
        }
        /// <summary>
        /// 执行一条sql语句
        /// </summary>
        /// <param name="sqlStr">sql语句</param>
        public static void ExecuteSql(string sqlStr)
        {
            try
            {
                SqlConnection con=GetCon.GetConnection();
                SqlCommand com = new SqlCommand(sqlStr, con);
                con.Open();
                com.ExecuteNonQuery();
            }
            catch (Exception e)
            {
                throw new Exception(e.Message);
            }
            finally
            {
                GetCon.GetClose();
            }
        }
        //关闭相关信息
        public static void GetClose()
        {
            try
            {
                if (dr != null)
                {
                    dr.Close();
                }
                if (com != null)
                {
                    com.Dispose();
                }
                if (da != null)
                {
                    da.Dispose();
                }
                if (conn != null)
                {
                    conn.Close();
                }
            }
            catch (Exception ex)
            {
                System.Console.Write(ex.ToString());
            }
        }

    }
}

你可能感兴趣的:(数据库)