C# 从表中检索行会导致无效列名错误
我正在尝试删除数据库表中的记录。我正试图根据下拉列表中选定的名称将其删除。当我调试代码时,dataset中没有任何可用的记录,并且出现一个无效列名的异常,而如果我在SQL Server中运行相同的查询,则一切似乎都正常 这是我的代码:C# 从表中检索行会导致无效列名错误,c#,sql,sql-server,C#,Sql,Sql Server,我正在尝试删除数据库表中的记录。我正试图根据下拉列表中选定的名称将其删除。当我调试代码时,dataset中没有任何可用的记录,并且出现一个无效列名的异常,而如果我在SQL Server中运行相同的查询,则一切似乎都正常 这是我的代码: protected void SubCategory_Delete_Click(object sender, EventArgs e) { try { var conn = new SqlConnection(@"Data Sour
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'
如果使用c版本>=6.0 您可以使用插值以非常方便且不易出错的方式来压缩字符串
var adpt = new SqlDataAdapter($"Select * from tc_prod_subcategory where subcategory_name = '{DropDownList2.SelectedItem.Value}'", conn);
该错误是由于where子句中的撇号位置不正确造成的。应该是这样的:
"Select * from tc_prod_subcategory where subcategory_name = '" + DropDownList2.SelectedItem.Value + "'"
但该代码易受攻击,因此应使用参数而不是串联字符串
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);
只需使用参数化查询。要想知道它为什么不起作用,您可以打印Select*from tc_prod_subcategory的结果,其中subcategory_name=''+DropDownList2.SelectedItem.ValueCheck我使用的是C 5版本,它不允许我这样写,有其他方法解决这个问题吗?是的,Rizwan,您可以使用SqlParameters或string.format格式化它