我对此问题感到非常困惑。我查看过以前的错误语法帖子'但他们有明显的例子。我有一些C#代码将DbContext查询代码写入我的数据库。我在相同的查询代码中更改了指向不同字符的错误:
db.Database.ExecuteSqlCommand("INSERT INTO AspNetUsers (Id, Email,
EmailConfirmed, PasswordHash, SecurityStamp, UserName, Location, First_Name,
Last_Name, Bio, Online_Collaboration, Instrument, Genre, PhoneNumberConfirmed,
TwoFactorEnabled, LockoutEnabled, AccessFailedCount) " +
"VALUES ('" + muser.Id + "', '" + muser.EmailAddress + "', 1, '" +
muser.SecurityStamp + "', '" + muser.Username + "', '" + muser.Location + "',
'" + muser.FirstName + "', '" + muser.LastName + "', '" + muser.Bio + "', 1,
0, 0, 0, 0, 0, 0)");
错误范围。这些是下面的一些示例,但是x'附近的语法。主要是这些字母之间的变化:
System.Data.SqlClient.SqlException: 'Incorrect syntax near 't'.'
System.Data.SqlClient.SqlException: 'Incorrect syntax near 'll'.
Unclosed quotation mark after the character string '', 1, 0, 0, 0, 0, 0, 0)'
System.Data.SqlClient.SqlException: 'Incorrect syntax near 'm'.
Unclosed quotation mark after the character string '', 1, 0, 0, 0, 0, 0, 0)'
System.Data.SqlClient.SqlException: 'Incorrect syntax near 's'.
Unclosed quotation mark after the character string '', 1, 0, 0, 0, 0, 0, 0)'
System.Data.SqlClient.SqlException: 'Incorrect syntax near 'm'.
Incorrect syntax near the keyword 'with'. If this statement is a common
table expression, an xmlnamespaces clause or a change tracking context
clause, the previous statement must be terminated with a semicolon.'
System.Data.SqlClient.SqlException: 'Incorrect syntax near 'll'.
Incorrect syntax near the keyword 'with'. If this statement is a common
table expression, an xmlnamespaces clause or a change tracking context
clause, the previous statement must be terminated with a semicolon.
Unclosed quotation mark after the character string '', 1, 0, 0, 0, 0, 0,
0)'.'
到目前为止我已经注意到了:
答案 0 :(得分:7)
永远不要通过连接字符串来创建SQL查询/命令。这不仅会让您容易受到SQL Injection的攻击,而且还会因为您亲身经历而导致字符串转义出现问题。
构建命令的正确方法是使用SqlParameter
。
var commandText = @"
INSERT INTO AspNetUsers
(Id, Email, EmailConfirmed, PasswordHash, SecurityStamp, UserName,
Location, First_Name, Last_Name, Bio, Online_Collaboration, Instrument,
Genre, PhoneNumberConfirmed, TwoFactorEnabled, LockoutEnabled,
AccessFailedCount)
VALUES
(@id, @email, 1, @securityStamp, -- and so on for other values
)
";
var idParameter = new SqlParameter("id", muser.Id);
var emailParameter = new SqlParameter("email", muser.EmailAddress);
var securityStampParameter = new SqlParameter("securityStamp", muser.SecurityStamp);
var parameters = new [] { idParameter, emailParameter, securityStampParameter };
db.Database.ExecuteSqlCommand(commandText, parameters);