【问题标题】:Retrieving a Row from a table causes invalid column name error从表中检索行导致无效列名错误
【发布时间】:2018-09-02 02:14:11
【问题描述】:

我正在尝试删除我的数据库表中的一条记录。我正在尝试根据下拉列表中的选定名称将其删除。当我调试我的代码时,数据集中没有任何可用记录,并且出现异常“列名无效”,而如果我在 SQL Server 中运行相同的查询,一切似乎都很好。

这是我的代码:

protected void SubCategory_Delete_Click(object sender, EventArgs e)
{
    try
    {
        var conn = new SqlConnection(@"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\template_castle.mdf;Integrated Security=True");
        var adpt = new SqlDataAdapter("Select * from tc_prod_subcategory where subcategory_name = ' ' "+ DropDownList2.SelectedItem.Value, conn);

        var ds = new DataSet();
        adpt.Fill(ds, "tc_prod_subcategory");

        foreach (DataRow dr in ds.Tables["tc_prod_subcategory"].Rows)
        {
            dr.Delete();
        }

        SqlCommandBuilder build = new SqlCommandBuilder(adpt);
        adpt.Update(ds, "tc_prod_subcategory");
        Updatesubcategorygrid();
        updatedelete_dropdown();
        Lblsub_catdelete.Text = "Deleted Successfully";
    }
    catch(Exception ex)
    {
        Lblsub_catdelete.Text = ex.Message;
    }
}

当我在 SQL Server 2014 中运行它时,这是同一个查询;一切正常:

Select * 
from tc_prod_subcategory 
Where subcategory_name= 'Favicon'

【问题讨论】:

  • 只使用参数化查询。要找出它不工作的原因,您可以打印出"Select * from tc_prod_subcategory where subcategory_name = ' ' "+ DropDownList2.SelectedItem.Value 的结果

标签: c# sql sql-server


【解决方案1】:

该错误是由where 子句中的撇号位置不正确引起的。应该是这样的:

"Select * from tc_prod_subcategory where subcategory_name = '" + DropDownList2.SelectedItem.Value + "'"

但该代码容易受到SQL injection 的攻击,因此您应该使用参数而不是连接字符串。

var conn = new SqlConnection(@"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\template_castle.mdf;Integrated Security=True");
var adpt = new SqlDataAdapter("Select * from tc_prod_subcategory where subcategory_name = @subcategory_name", conn);
var ds = new DataSet();

adpt.SelectCommand.Parameters.AddWithValue("@subcategory_name", DropDownList2.SelectedItem.Value);

【讨论】:

    【解决方案2】:

    如果你使用 c# 版本 >= 6.0

    您可以使用插值以非常方便且不易出错的方式连接字符串。

     var adpt = new SqlDataAdapter($"Select * from tc_prod_subcategory where subcategory_name = '{DropDownList2.SelectedItem.Value}'", conn);
    

    【讨论】:

    • 我使用的是 C# 5 版本
    • 不允许我这样写,有没有其他办法解决这个问题?
    • 是 Rizwan,你可以使用 SqlParameters 或使用 string.Format 格式化它
    猜你喜欢
    • 2019-11-27
    • 1970-01-01
    • 1970-01-01
    • 2016-01-17
    • 1970-01-01
    • 2021-10-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多