SqlConnection,SqlCommand,SqldataReader

来源:互联网 发布:朱棣和宁王 知乎 编辑:程序博客网 时间:2024/05/16 08:48
 

来自http://hi.baidu.com/%B1%BF%BA%FC%C0%EA_xy/blog/item/6c414f85672112f8bd3e1e2a.html

 

       对于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();

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

原创粉丝点击