您的位置:首页 > 数据库

ADO.NET之command查询数据

2016-01-09 10:37 295 查看
执行结果:





 

C# ->新建空网站->添加新项WEB窗体

 

cs代码:

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)

    {

        if (!IsPostBack)

        {

            this.bind();

        }   

    }

    public SqlConnection GetConnection()

    {

        string Str = ConfigurationManager.AppSettings["ConnectionString"].ToString();

        SqlConnection Conn = new SqlConnection(Str);

        return Conn;

    }

    protected void bind()

    {

        SqlConnection myConn = GetConnection();

        myConn.Open();

        string sqlStr = "select * from t001";

        SqlDataAdapter myDa = new SqlDataAdapter(sqlStr, myConn);

        DataSet myDs = new DataSet();

        myDa.Fill(myDs);

        GridView1.DataSource = myDs;

        GridView1.DataBind();

        myDa.Dispose();

        myDs.Dispose();

        myConn.Close();

    }

  

    protected void btnSelect_Click(object sender, EventArgs e)

    {

        if (this.txtName.Text != "")

        {

            SqlConnection myConn = GetConnection();

            myConn.Open();

            string sqlStr = "select * from t001 where
bukrs=@Name";

            SqlCommand myCmd = new SqlCommand(sqlStr, myConn);

            myCmd.Parameters.Add("@Name", SqlDbType.VarChar, 20).Value = this.txtName.Text.Trim();

            SqlDataAdapter myDa = new SqlDataAdapter(myCmd);

            DataSet myDs = new DataSet();

            myDa.Fill(myDs);

            if (myDs.Tables[0].Rows.Count > 0)

            {

                GridView1.DataSource = myDs;

                GridView1.DataBind();

            }

            else

            {

                Response.Write("<script>alert('没有相关记录')</script>");

            }

            myDa.Dispose();

            myDs.Dispose();

            myConn.Close();

        }

        else

            this.bind();

    }

}

 

配置文件代码:

<configuration>

  <appSettings>
    <add key="ConnectionString" value="Data Source=.\SQLEXPRESS;AttachDbFilename=C:\DataBase\sap.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True"/>
  </appSettings>

  <connectionStrings/>

  <system.web>

    <compilation debug="true" targetFramework="4.0"/>

    <authentication mode="Windows"/>

    <pages controlRenderingCompatibilityVersion="3.5" clientIDMode="AutoID"/>

  </system.web>

</configuration>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  C# ADO.NET COMMAND SQL