请教c#中using的正确使用方法操作数据库

xiehuangda xiehuangda 墨衍会员 · AI 创作全网分发 墨衍智能分发 通过墨衍一键同步至各平台 可同步平台 CSDN微信公众号微博知乎掘金百家号博客园抖音小红书 你的文章也可以这样分发 墨衍会员 ¥399起/年,写一次发全网 我也要 + 加入社区
请教c#中using的正确使用方法操作数据库
c#中创建一个类Conn 设置cn为private 这是规定好的,cn不能改为public

class Conn
{
private static string cn = "Data Source=192.168.1.8,1433;Initial Catalog=Data2020;User ID=sa;pwd=abc123";
public static SqlConnection rs = new SqlConnection(cn);
}


创建一个窗体Form1 在Form1_Load中写入3个例子的代码。使用using(..){..} 来操作数据库。

//例子1
try
{
string sql = "Select * From tTable Where tID='1'";
SqlCommand cmd = new SqlCommand(sql, Conn.rs);
Conn.rs.Open();
SqlDataReader dr = cmd.ExecuteReader();
dr.Read();
this.Text = dr["LoginTitle"].ToString();
dr.Close();
cmd.Clone();
}
catch (Exception er)
{
MessageBox.Show(er.Message);
}
finally
{
Conn.rs.Close();
}


//例子2
try
{
string sql = "Select * From tTable Where tID='1'";
using (SqlCommand cmd = new SqlCommand(sql, Conn.rs))
{
Conn.rs.Open();
using (SqlDataReader dr = cmd.ExecuteReader())
{
dr.Read();
this.Text = dr["LoginTitle"].ToString();
dr.Close();
}
cmd.Clone();
}
}
catch (Exception er)
{
MessageBox.Show(er.Message);
}
finally
{
Conn.rs.Close();
}


//例子3
try
{
string sql = "Select * From tTable Where tID='1'";
using (SqlCommand cmd = new SqlCommand(sql, Conn.rs))
{
Conn.rs.Open();
using (SqlDataReader dr = cmd.ExecuteReader())
{
dr.Read();
this.Text = dr["LoginTitle"].ToString();
dr.Close();
}
cmd.Clone();
Conn.rs.Close();
}
}
catch (Exception er)
{
MessageBox.Show(er.Message);
}


请教using的正确使用方法是哪个例子?才算正确操作数据库。
或者,大家有更好的方法正确写using吗?帮忙写出来指正一下。
谢谢大家!
...全文
评论 7
收藏 已收藏
分享
返回顶部
xiehuangda
C# 111,130 成员 642,541 内容