[英]C# String literal with concatenation
I have a ASP.NET C# application, and I frequently use the verbatim string literal such as 我有一个ASP.NET C#应用程序,并且经常使用逐字字符串文字,例如
dbCommand.CommandText = @"INSERT INTO MYTABLE (COLUMN, COLUMN2)
VALUES ('data', 'data)";
This is all great, but when I try to concatenate the string with a variable such as 一切都很好,但是当我尝试使用诸如
dbCommand.CommandText = @"INSERT INTO MYTABLE" + Session["table_extension"] + "(COLUMN, COLUMN2)
VALUES('data','data')";
I get an error stating Newline in constant. 我收到一个错误,指出常量中的换行符。 How can I avoid this while still using the @ string literal?
在仍使用@字符串文字的情况下如何避免这种情况?
将@放在第二个字符串文字的前面,或使用String.Format()
1) Don't concatenate strings to build SQL commands, it's really dangerous and error phrone (see SQL Injection: http://www.w3schools.com/sql/sql_injection.asp ). 1)不要串联字符串来构建SQL命令,这确实是危险和错误的消息(请参阅SQL Injection: http : //www.w3schools.com/sql/sql_injection.asp )。
You should use ADO.NET parameters ( http://www.csharp-station.com/Tutorial/AdoDotNet/Lesson06 ) 您应该使用ADO.NET参数( http://www.csharp-station.com/Tutorial/AdoDotNet/Lesson06 )
2) If you are going to concatenate strings, use string.Format like: 2)如果要连接字符串,请使用string.Format,例如:
var sql = string.Format("INSERT INTO MyTable ('col1') VALUES ({0})", col1Value);
Or use the new simplified syntax which has a better compile time check: 或者使用新的简化语法,它具有更好的编译时间检查:
var sql = $"INSERT INTO MyTable (col1) VALUES ('{col1Value}')";
This will work for you! 这将为您工作!
dbCommand.CommandText = @"INSERT INTO MYTABLE" + Session["table_extension"].ToString() + "(COLUMN, COLUMN2)
VALUES('data','data')";
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.