我在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(); }
尝试删除单引号。另外,为什么还要将SQL字符串与连接对象(.. word='@word'" + conn)连接起来????
.. 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; } ...
还要注意,由于连接被包装在using块中,因此您无需在finally语句中将其关闭。Dispose方法将自动调用.Close方法,该方法会将连接返回到ADO.NET连接池,以便可以重用它。
finally
另一点是,这种IncludeWord方法在很多事情上都做得很好。它发送SQL查询以删除记录,它在GUI上更新一些文本框,并绑定一些列表=>这样的方法应该分开分开,这样每个方法都有其特定的职责。否则,此代码只是维护方面的噩梦。我强烈建议您编写仅执行单个特定任务的方法,否则代码很快就会变成一团糟。
IncludeWord