理解SqlConnection,SqlCommand,SqldataReader

本文详细介绍了使用SqlConnection、SqlCommand及SqlDataReader进行数据库操作的四种常见方式,并解释了它们之间的关系,有助于初学者更好地理解和掌握这些核心组件。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

以前写机房收费系统的时候数据库连接这一块就没怎么弄明白,这次有机会了得把这部分内容好好看看···

对于SqlConnection,SqlCommand,SqldataReader的使用和他们之间的关系不是很清楚下面对SqlConnection,SqlCommand,SqldataReader的几种配合使用的方式进行了总结:


第一种:
SqlConnection con
= new
SqlConnection();
con.ConnectionString
= "server=.;database=northwind;uid=sa;pwd=;"; //双引号中的最后一个分号可以去掉

con.Open();
SqlCommand cmd
=
con.CreateCommand();
cmd.CommandText
= "select * from customers"
;
SqlDataReader sdr
=
cmd.ExecuteReader();
this.GridView1.DataSource =
sdr;
this
.GridView1.DataBind();
sdr.Close();
con.Close();
第二种:
SqlConnection con = new SqlConnection();
con.ConnectionString = "server=.;database=northwind;uid=sa;pwd=;"; //
双引号中的最后一个分号可以去掉
con.Open();
SqlCommand cmd = new SqlCommand("select * from customers");
cmd.Connection = con;
SqlDataReader sdr = cmd.ExecuteReader();
this.GridView1.DataSource = sdr;
this.GridView1.DataBind();
sdr.Close();
con.Close();


第三种:
最经常用这一种,同时连接对象是整个程序的公共对象,所以我一般会把数据库连接封装到一个类中,这样就可以在程序的任何地方随时调用
SqlConnection con = new SqlConnection("server=.;database=northwind;uid=sa;pwd=;"); //双引号中的最后一个分号可以去掉
con.Open();
SqlCommand cmd = new SqlCommand("select * from customers", con);
SqlDataReader sdr = cmd.ExecuteReader();
this.GridView1.DataSource = sdr;
this.GridView1.DataBind();
sdr.Close();
con.Close();

第四种:
SqlConnection con = new SqlConnection();
con.ConnectionString = "server=.;database=northwind;uid=sa;pwd=;"; //
双引号中的最后一个分号可以去掉
con.Open();
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
cmd.CommandText = "select * from customers";
cmd.CommandType = CommandType.Text; //
这条语句是多余的,因为默认就是Text
SqlDataReader sdr = cmd.ExecuteReader();
this.GridView1.DataSource = sdr;
this.GridView1.DataBind();
sdr.Close();
con.Close();

虽然这四种方法大同小异,但是对于初学者理解三者之间的关系和掌握这种方法还是很有帮助的。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值