从数据库中查找特定数据?

时间:2014-10-26 17:37:49

标签: c# asp.net

我在C#编码。我想搜索一个名字。我想从我连接的数据库中显示该人的详细信息。但我得到的只是

  

错误"使用未分配的局部变量。

我也尝试初始化变量。它执行但没有显示输出。

这是我的代码......

public partial class _Default : System.Web.UI.Page
{
    protected void Button1_Click(object sender, EventArgs e)
    {
        SqlConnection cn = new SqlConnection("SERVER=MITHILESH-PC\\SERVER101;Initial Catalog=People;Integrated Security=True");

        String find = " ";
        TextBox1.Text = find;

        String QueryString = "Select * from Members Where NAME='{find}' ";
        SqlCommand cmd = new SqlCommand(QueryString,cn);

        SqlDataReader dr = null;

        cn.Open();
        dr = cmd.ExecuteReader();

        GridView1.DataSource = dr;
        GridView1.DataBind();

        cn.Close();
    }
}

1 个答案:

答案 0 :(得分:3)

String QueryString = "Select * from Members Where NAME=@Name ";
SqlCommand cmd = new SqlCommand(QueryString,cn);
cmd.Parameters.AddWithValue("@Name", TextBox1.Text);

将值添加为SqlCommand的参数,这是正确的方法。在这种情况下,您也将阻止SQL注入攻击。

同样在你的代码的乞讨中:

String find = " ";
TextBox1.Text = find;

在这里,您将复选框的文本等于“”。如果要将textBox值存储在变量find中,则应按如下方式编写:string find = TextBox1.Text;