我对这个问题感到非常困惑.我查看过以前的'错误语法'帖子,但他们有明确的例子.我有一些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)");
Run Code Online (Sandbox Code Playgroud)
错误范围.这些是下面的一些示例,但'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)'.'
Run Code Online (Sandbox Code Playgroud)
到目前为止我注意到了什么:
永远不要通过连接字符串来创建SQL查询/命令.这不仅使您容易受到SQL注入的攻击,而且还会导致您亲自体验字符串转义问题.
构建命令的正确方法是使用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);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
177 次 |
| 最近记录: |