尝试将数据库条目限制为当前UserName

时间:2014-05-23 15:05:02

标签: c# asp.net sql

我使用上传文件的人的UserName更新数据库,并尝试仅检索当前用户上传的文件,以显示在gridview中。

页面显示当前用户名,当该人上传文件时,一切正常。虽然当该用户点击搜索按钮时,所有记录都会显示,但我收到错误:

错误:列名'test'无效

  protected void ButtonSearch_Click(object sender, EventArgs e)
{
    GridView1.Visible = true;

    try
    {
        string UN = Session["New"].ToString();
        SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);


        SqlDataReader reader;
        SqlCommand command = new SqlCommand();
        command.CommandText = "SELECT * FROM UserUpload WHERE UserName = @un";
        command.Parameters.Add(new SqlParameter("@un", UN));
        command.Connection = conn;

        conn.Open();

            reader = command.ExecuteReader();

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

        conn.Close();

        }

    catch (Exception ex)
    {

        LabelMessage.Text = ("Error:" + ex.Message);

    }
}

2 个答案:

答案 0 :(得分:2)

更改此行

string UserSearch = "SELECT * FROM UserUpload WHERE UserName =" + UN;

string UserSearch = string.Format("SELECT * FROM UserUpload WHERE UserName ='{0}'",UN);

您希望匹配用户名,因为字符串字符串包含在'''在SQL中 如果您将按编号进行匹配,则可以正常工作,因为数字没有此要求。

更新到更新: 更改为(未经测试)

之类的内容
SqlCommand com = new SqlCommand(UserSearch, conn);

    {   DataSet ds = com.ExecuteReader();
        if (ds.Tables.Count > 0)
        {
            GridView1.DataSource = ds;
            GridView1.DataBind();
        }
            conn.Close();
    }

您可以阅读this

答案 1 :(得分:2)

使用参数而不是将值分配给查询字符串

    protected void ButtonSearch_Click(object sender, EventArgs e)
    {
        GridView1.Visible = true;
        try
        {
            string UN = Session["New"].ToString(); ;
            SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
            conn.Open();
            string UserSearch = "SELECT * FROM UserUpload WHERE UserName = @un";
            SqlCommand com = new SqlCommand(UserSearch, conn);
            com.Parameters.Add(new SqlParameter("@un", UN));

            com.ExecuteNonQuery();
            conn.Close();
        }
        catch (Exception ex)
        {

            LabelMessage.Text = ("Error:" + ex.Message);

        }
    }