在C#中创建SqlDbConnection类 [英] Creating a SqlDbConnection class in C#
问题描述
我正在尝试为我的应用程序创建一个SqlDbConnection类文件。我希望使用此连接类在需要时连接到数据库。到目前为止我的课程代码是:
I'm trying to create a SqlDbConnection class file for my application. And I want use this connection class to connect to the database whenever it requires. Till now what I have for the class code is:
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.Dispose方法,因此它将关闭并处置SqlConnection。现在我对我应该如何在SqlDbConnection类文件中使用Dispose()方法感到困惑。因此,非常感谢任何相关指南。
I guess that I need to call the DbConnection.Dispose Method, so it will close and dispose of the SqlConnection. Now I'am bit confused with how exactly I should use the Dispose() method on my SqlDbConnection class file. So any related guideline would be much appreciated.
推荐答案
将接口IDisposable添加到您的班级定义:
Add the Interface IDisposable to your class definition:
public class SqlDbConnection : IDisposable
然后添加Dispose方法:
Then add the Dispose method:
public void Dispose()
{
if (cmd != null)
{
cmd.Dispose();
cmd = null;
}
if (sda != null)
{
sda.Dispose();
sda = null;
}
if (dt != null)
{
dt.Dispose();
dt = null;
}
if (con != null)
{
if (con.State == ConnectionState.Open) con.Close();
con.Dispose();
con = null;
}
}
这里有一个很好的讨论:正确实现IDisposable和Dispose模式 [ ^ ]非常值得一读。
There is a good discussion on this here: Implementing IDisposable and the Dispose Pattern Properly[^] which is well worth a read.
这篇关于在C#中创建SqlDbConnection类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!