1

下面是我精简的 C#:

thisConnection.Open();
string commandtext = "Insert into Table (Comments)values('@Comments')";
SqlCommand command = new SqlCommand(commandtext, thisConnection);
command.Parameters.Add("@Comments", SqlDbType.VarChar).Value = Comments;
command.ExecuteNonQuery();
thisConnection.Close();

我几乎可以输入任何东西,在输入数据库之前删除某些特殊字符,这对我来说很好,即使是一个单引号也会在工作中引发扳手。我已经尝试添加.Replace("'","''");Comments变量中,但这并没有改变任何东西,尽管使用参数应该可以防止这种情况发生。

我知道这样的问题被问了很多,但到处都只是指向“使用参数!”


编辑:看到四个人说了同样的话,我在这里全部回复。我已经删除了周围的单引号@Comments,但问题是完全相同的。任何带单引号的输入根本不会输入到数据库中。

.replace(/'/g,"''")在我们使用 javascript 之前,我已经添加了,这是有效的,但我不明白为什么我应该这样做。

4

5 回答 5

2

您不需要单引号。

command.CommandText = "Insert into Table (Comments)values(@Comments)";

好的,在 的评论之后阅读了一下hvd,我看到它的工作方式是通过执行sp_executesql.

解决此问题的方法可能如下:

thisConnection.Open();
SqlCommand command = new SqlCommand(commandtext, thisConnection);
command.CommandText = "Insert into Table (Comments)values(@Comments)";
SqlParameter param  = new SqlParameter();
param.ParameterName = "@Comments";
param.Value         = Comments;
command.Parameters.Add(param);
command.ExecuteNonQuery();
thisConnection.Close();
于 2013-09-27T09:21:11.747 回答
0

它应该如图所示:

cmd.CommandText = "INSERT INTO Table (Comments) VALUES(@Comments)"
于 2013-09-27T09:22:18.527 回答
0

使用参数时不必转义单引号。
假设这Comments是类型,String那么只需执行以下操作:

command.CommandText = "Insert into Table (Comments)values(@Comments)";
command.Parameters.Add("@Comments", SqlDbType.VarChar).Value = Comments;
于 2013-09-27T09:22:37.803 回答
0
"Insert into Table (Comments)values('@Comments')";

应该

"Insert into Table (Comments)values(@Comments)"; <-- no single quotes

人们建议您使用的原因parameters是避免SQL injection. 看看Bobby Tables

于 2013-09-27T09:22:46.890 回答
0

我已经尝试过这样的事情,但我没有得到任何异常,但对于 SQL 注入来说可能不安全。

Comments.Replace("'", $"{(char)39}");
于 2019-09-09T19:55:06.367 回答