使用Visual Studio 2015和SQL Server 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");
答案 0 :(得分:2)
一旦你弄清楚如何正确地转义它(使用@或\),没有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);
答案 1 :(得分:0)
使用字符串上的前导@转义@字符。
SqlCommand cmd = new SqlCommand(@"Insert into Products(Id,Name,[Description],Price,IsAvailable) Values(@Id, @Name, @Description, @Price)", yourConnection);