SqlDataReader

 

第二讲

1.       Command对象的任用?

用于对数据库发出SQL命令,从而执行添加,修改,删除等操作

2.       Command 对象两个主要方法

ExecuteNonQuery方法:执行命令并返回受影响的行数

ExecuteReader方法:执行命令并返回生成DataReader

3.       DataReader对象的作用?

返回一个来自数据命令的只读,只进的数据流

语法:

SqlCommand对象名=new SqlCommand(“sql语句 “,Connection实例化对象);

 

实例化对象:是声明的连接

using System;

using System.Data;

using System.Configuration;

using System.Web;

using System.Web.Security;

using System.Web.UI;

using System.Web.UI.WebControls;

using System.Web.UI.WebControls.WebParts;

using System.Web.UI.HtmlControls;

 

using System.Data.SqlClient;

public partial class _Default : System.Web.UI.Page

{

    protected void Page_Load(object sender, EventArgs e)

    {

        //与数据库进行连接

        string strCon = System.Configuration.ConfigurationManager.ConnectionStrings["testconnectionString"].ToString();

        //创建SqlConnection对象

        SqlConnection sqlCon = new SqlConnection(strCon);

        //打开连接

        sqlCon.Open();

           

        //进行数据添加

        SqlCommand insertCom =new SqlCommand("insert into info (name,sex) values('张三','')",sqlCon);

        //执行返回受影响的行数

        insertCom.ExecuteNonQuery();

            //查询数据

        SqlCommand selectSql = new SqlCommand("select * from info ", sqlCon);

        SqlDataReader readerCon = selectSql.ExecuteReader();

        while (readerCon.Read())

        {

            Response.Write(readerCon["name"]);

            Response.Write(readerCon["sex"]);

            Response.Write("<br>");

        }

        readerCon.Close();

        //更新数据

        SqlCommand updateSql = new SqlCommand("update  info set name='张三'", sqlCon);

        updateSql.ExecuteNonQuery();

       

        //删除数据

        SqlCommand deleteSql = new SqlCommand("delete from info where name='张三'", sqlCon);

        deleteSql.ExecuteNonQuery();

        Response.Write("数据已删除");

        //再查询数据

 

        SqlDataReader sdr = selectSql.ExecuteReader();

         while (sdr.Read())

         {

             Response.Write(sdr["name"]);

             Response.Write(sdr["sex"]);

             Response.Write("<br>");

         }

         sdr.Close();

 

    }

}

 

 

你可能感兴趣的:(SqlDataReader)