命名 SQL 序列的连接字符串中无法识别的转义序列错误

Unrecognized escape sequence error in named SQL sequence's connection string

使用 Visual Studio 2015 和 SQL 服务器 2014。

我已经尝试了所有方法,包括使用“[]”、使用双反斜杠和“@”,但仍然会出现无法识别的转义序列错误。还有其他解决方案吗?

SqlCommand cmd = new SqlCommand("Insert into Products(Id,Name,[Description],Price,IsAvailable) Values(@Id, @Name, @Description, @Price, @IsAvailable)", "Data Source=.\MSSQLSERVER1;Initial Catalog=ProductDB;Integrated Security=True");

在字符串中使用前导 @ 转义 @ 字符。

SqlCommand cmd = new SqlCommand(@"Insert into Products(Id,Name,[Description],Price,IsAvailable) Values(@Id, @Name, @Description, @Price)", yourConnection);

一旦您弄清楚如何正确地转义连接字符串(使用 @ 或 \),SqlCommand 的构造函数就不会采用连接字符串,如下所示:

var conn=new SqlConnection(@"Data Source=.\MSSQLSERVER1;Initial Catalog=ProductDB;Integrated Security=True");
SqlCommand cmd = new SqlCommand("Insert into Products(Id,Name,[Description],Price,IsAvailable) Values(@Id, @Name, @Description, @Price, @IsAvailable)", conn);

var conn=new SqlConnection("Data Source=.\MSSQLSERVER1;Initial Catalog=ProductDB;Integrated Security=True");
SqlCommand cmd = new SqlCommand("Insert into Products(Id,Name,[Description],Price,IsAvailable) Values(@Id, @Name, @Description, @Price, @IsAvailable)", conn);