【问题标题】:'Incorrect syntax near '2'.' [closed]''2' 附近的语法不正确。' [关闭]
【发布时间】:2018-10-25 15:39:52
【问题描述】:

我试图从基于 sql 的用户输入中检索行数并在 gridview 中显示

请帮忙!

Int32 text = Convert.ToInt32(this.Txtusers.Text);
con.Open();
cmd = new SqlCommand("select TOP '" + text + "' * from Avaya_Id where LOB = '" + DDLOB.SelectedItem.Value + "' and Status = 'Unassigned'", con);
SqlDataReader rdr = cmd.ExecuteReader();
GridView1.DataSource = rdr;
GridView1.DataBind();
con.Close();

【问题讨论】:

标签: c# sql select


【解决方案1】:

这是应该如何写的。

int text;
if(int.TryParse(this.Txtusers.Text, out text)
{
    using(var con = new SqlConnection(connectionString)
    {
        using(var cmd  = new SqlCommand("select TOP (@top) * from Avaya_Id where LOB = @LOB and Status = 'Unassigned'", con))
        {
            cmd.Parameters.Add("@top", SqlDbType.Int).Value = text;
            cmd.Parameters.Add("@LOB", SqlDbType.Int).Value = DDLOB.SelectedItem.Value;
            con.Open();
            using(var rdr = cmd.ExecuteReader())
            {
                GridView1.DataSource = rdr;
                GridView1.DataBind();
            }
        }
    }
}

兴趣点:

  • 使用参数来避免 Sql Injection 的风险。
  • Convert.ToInt32 更改为int.TryParse。永远不要相信用户输入。
  • 对每个实现IDisposable 接口的实例使用using 语句。
  • 请注意,使用 top x 而不使用 order by 子句意味着您从数据库中获取 x 条任意记录 - 因为数据库表本质上是无序的,并且是确保从 select 返回的行的顺序的唯一方法语句是使用order by 子句。

请注意我已经猜到第二个参数是int,如果不是,请更改数据类型。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-03-22
    • 2020-11-03
    • 2013-06-26
    • 2020-02-07
    • 1970-01-01
    • 1970-01-01
    • 2013-12-16
    • 2011-05-28
    相关资源
    最近更新 更多