在c#中创建SqlDbConnection类

本文关键字:SqlDbConnection 创建 | 更新日期: 2023-09-27 18:08:11

我试图为我的应用程序创建一个SqlDbConnection类文件。我想使用这个连接类在需要时连接到数据库。到目前为止,我的类代码是:

using System.Data.Sql;
using System.Data.SqlClient;
using System.Data;
namespace SqlTesting
{
public class SqlDbConnection
{
    private SqlConnection con;
    public SqlCommand cmd;
    private SqlDataAdapter sda;
    private DataTable dt;
    public SqlDbConnection()
    {
        con = new SqlConnection("Data Source=.''SQLEXPRESS;Initial Catalog=DB_SQL;Integrated Security=SSPI;");
        con.Open();
    }
    public void SqlQuery(string querytext)
    {
        cmd = new SqlCommand(querytext, con);
    }
    public DataTable QueryEx()
    {
        sda = new SqlDataAdapter(cmd);
        dt = new DataTable();
        sda.Fill(dt);
        return dt;
    }
    public void NonQueryEx()
    {
        cmd.ExecuteNonQuery();
    }
}
}

我想我需要调用DbConnection。方法,因此它将关闭并处置SqlConnection。现在我有点困惑,我应该如何在我的SqlDbConnection类文件上使用Dispose()方法。因此,任何相关的指导方针将不胜感激。

在c#中创建SqlDbConnection类

对所有实现iDisposable的对象调用Dispose/Close总是很重要的。当然,这意味着SqlDBConnection。

可支配资源

常见的一次性资源包括:

 1.Database-related
    classes: SqlConnection, SqlDataReader, and SqlTransaction.
 2. File-based classes: FileStream and BinaryWriter. Stream-based
    classes: StreamReader, TextReader, TextWriter, BinaryReader, and
    TextWriter. 
 3. Network-based classes: Socket, UdpClient, and TcpClient.

查看指南的一个好地方是微软最佳实践:http://msdn.microsoft.com/en-us/library/ff647790.aspx scalenetchapt05_topic11

首先你需要使用SqlDbConnection : IDisposable

使用后

       public void Dispose()
        {
            con.Close();                
            cmd.Dispose();
        }