I have a ASP.NET C# application, and I frequently use the verbatim string literal such as
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 ).
You should use ADO.NET parameters ( http://www.csharp-station.com/Tutorial/AdoDotNet/Lesson06 )
2) If you are going to concatenate strings, use string.Format like:
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')";
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.