我在SQL中遇到一个带有意外结果的简单DELETE语句时出现问题,它似乎将该单词添加到列表中.一定是傻事!但我看不到它,尝试了几种不同的方式.所有相同的结果都很混乱.
public void IncludeWord(string word)
{
// Add selected word to exclude list
SqlConnection conn = new SqlConnection();
String ConnectionString = "Data Source = dev\\SQLEXPRESS ;" + "Initial Catalog=sml;" + "User id=** ;" + "Password =*;" + "Trusted_Connection=No";
using (SqlConnection sc = new SqlConnection(ConnectionString))
{
try
{
sc.Open();
SqlCommand Command = new SqlCommand(
"DELETE FROM excludes WHERE word='@word'" +
conn);
Command.Parameters.AddWithValue("@word", word);
Command.ExecuteNonQuery();
}
catch (Exception e)
{
Box.Text = "SQL error" + e;
}
finally
{
sc.Close();
}
ExcludeTxtbox.Text = "";
Box.Text = " Word : " + word + " has been removed from the Exclude List";
ExcludeLstBox.AppendDataBoundItems = false;
ExcludeLstBox.DataBind();
}
Run Code Online (Sandbox Code Playgroud)
Dar*_*rov 17
尝试删除单引号.另外,为什么要将SQL字符串与连接对象连接(.. word='@word'" + conn)?
试试这样:
try
{
using (var sc = new SqlConnection(ConnectionString))
using (var cmd = sc.CreateCommand())
{
sc.Open();
cmd.CommandText = "DELETE FROM excludes WHERE word = @word";
cmd.Parameters.AddWithValue("@word", word);
cmd.ExecuteNonQuery();
}
}
catch (Exception e)
{
Box.Text = "SQL error" + e;
}
...
Run Code Online (Sandbox Code Playgroud)
另请注意,由于连接包含在using块中,因此您无需在finally语句中将其关闭.Dispose方法将自动调用.Close方法,该方法将返回到ADO.NET连接池的连接,以便可以重用它.
另一个评论是,这种IncludeWord方法可以做很多事情.它发送SQL查询来删除记录,它更新GUI上的一些文本框,它绑定一些列表=>这样的方法应该分开拆分,以便每个方法都有自己的特定职责.否则,此代码只是维护方面的噩梦.我强烈建议你编写只执行一个特定任务的方法,否则代码会很快变得完整.