C# database封装

来源:互联网 发布:神经网络算法过程 编辑:程序博客网 时间:2024/05/16 09:44

public class database
{
 
    public static string GetConnectionString()
    {
        string conStr = ConfigurationManager.ConnectionStrings["BMSConnectionString"].ConnectionString;
        return conStr;
    }

    public static int ExecuteNonQuery(string commandText)
    {
        try
        {
            SqlConnection conn;
            SqlCommand command;
            conn = new SqlConnection();
            conn.ConnectionString = GetConnectionString();
            command = new SqlCommand();
            command.CommandText = commandText;
            command.CommandType = CommandType.Text;
            command.Connection = conn;
            command.Connection.Open();

            int rs = command.ExecuteNonQuery();
                  }  
        catch(SqlException ex)
        {
            throw ex;
        }

        finally

        {

            command.Connection.Close();
            command.Dispose();
            conn.Dispose();
            return rs;

        }
       
 
    }

    public static DataTable ExecuteDataTable(string commandText)
    {
        try
        {
            SqlConnection conn;
            SqlCommand command;
            SqlDataAdapter sda;
            DataTable table = new DataTable();

            conn = new SqlConnection();
            conn.ConnectionString = GetConnectionString();

            command = new SqlCommand();
            command.CommandText = commandText;
            command.CommandType = CommandType.Text;
            command.Connection = conn;
            command.Connection.Open();

            sda = new SqlDataAdapter();
            sda.SelectCommand = command;
            sda.Fill(table);

        }
        catch (SqlException ex)
        {
            throw ex;
        }        

        finally

        {

            sda.dispose();

            command.Connection.Close();
            command.Dispose();
            conn.Dispose();
            return table;

        }
    }

 

}