Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/295.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# SQL server-插入带单引号的字符串_C#_Sql Server_Dml - Fatal编程技术网

C# SQL server-插入带单引号的字符串

C# SQL server-插入带单引号的字符串,c#,sql-server,dml,C#,Sql Server,Dml,我迭代了一个外部源,得到了一个字符串列表。然后,我使用以下命令将它们插入数据库: SqlCommand command = new SqlCommand(commandString, connection); command.ExecuteNonQuery(); 其中commandString是插入到命令中的命令。i、 e insert into MyTable values (1, "Frog") 有时字符串包含“或”或\且插入失败。 是否有一种优雅的方法来解决此问题(即@“”或类似问题

我迭代了一个外部源,得到了一个字符串列表。然后,我使用以下命令将它们插入数据库:

SqlCommand command = new SqlCommand(commandString, connection);
command.ExecuteNonQuery();
其中commandString是插入到命令中的命令。i、 e

insert into MyTable values (1, "Frog") 
有时字符串包含“或”或\且插入失败。

是否有一种优雅的方法来解决此问题(即@“”或类似问题)?

您应该研究使用参数化查询。这将允许您插入数据,而不管内容如何,也有助于避免将来可能的SQL注入


您应该研究使用参数化查询。这将允许您插入数据,而不管数据的内容如何,也有助于避免将来可能的SQL注入

参数

insert into MyTable values (@id, @name) 

现在,
name
可以有任意数量的引号,并且可以正常工作。更重要的是,它现在可以避免sql注入

像“dapper”(在NuGet上免费提供)这样的工具使这更容易:

int id = 1;
string name = "Fred";
connection.Execute("insert into MyTable values (@id, @name)",
    new { id, name });
参数

insert into MyTable values (@id, @name) 

现在,
name
可以有任意数量的引号,并且可以正常工作。更重要的是,它现在可以避免sql注入

像“dapper”(在NuGet上免费提供)这样的工具使这更容易:

int id = 1;
string name = "Fred";
connection.Execute("insert into MyTable values (@id, @name)",
    new { id, name });

使用参数化查询?使用参数化查询?