<random changing =“”character =“”>

时间:2018-04-16 12:45:01

标签: c# sql dbcontext

我对此问题感到非常困惑。我查看过以前的错误语法帖子&#39;但他们有明显的例子。我有一些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&#39;附近的语法。主要是这些字母之间的变化:

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)'.'

到目前为止我已经注意到了:

  • 字符主要是s,t,m和ll。 &#39;&#39;&#39;意味着它不能只是一个字符问题。这些字符在整个代码中经常使用,因此我无法确定这些字符,尽管我认为它们是症状,而不是原因。
  • x&#39;附近的语法不正确是唯一一致的错误。我相信其他人只是后续行动。在我运行它的几十次中,它是最小的消息。
  • 最后是最令人沮丧的部分 - 它很少工作(非常),所以语法应该很好,据我所见。也许它在游行结束时会出现问题并且一些时间重叠?变量有一些字符串断裂,但我认为这是相当标准的负载。

1 个答案:

答案 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);