有人能帮助我理解我在下面的代码中做错了吗?:
//....
internal static string InsertCorrespondenceRecipientItem(TbEmail email, Guid correspondenceId, Guid contactId) => $@"
INSERT INTO CorrespondenceRecipientItems
(Id, DateSent, Subject, ToEmail, [CorrespondenceId] , [ToId], [CorrespondenceRecipientId])
VALUES
('{email.Guid}', '{email.DateSent}', @subject, @emailString, '{correspondenceId}', '{contactId}', '{email.Guid}')
";
var sqlItemsUpdate = SqlHelpers.InsertCorrespondenceRecipientItem(item.email, correspondence.Guid, fromId);
var subject = item.email.Subject.Trim();
var emailString = item.email.EmailAddressString.Trim();
await _db.Database.ExecuteSqlCommandAsync(sqlItemsUpdate, new SqlParameter("@subject", subject), new SqlParameter("@emailString", emailString));
数据库中的结果是
'7F856136-0036-4F68-249F-08D5AB631656', @subject, @emailString
为什么执行没有设置参数的值?
答案 0 :(得分:1)
我希望你需要一个有效的解决方案,而不是原因,为什么另一个不起作用......:
//....
var subject= "test";
var emailString ="dot.dot@dot.com";
await _db.Database
.ExecuteSqlCommandAsync($"INSERT INTO Table(Id, Subject, Email) VALUES (NEWID(), {subject }, {emailString})");
编辑: 正如评论中所提到的,我将不得不解释一个带有上述参数的插值字符串,如果它是内联声明的,将由EF-Core进行参数化。
以下语句未参数化,因此确实容易受到sql-injection的攻击:
//....
var subject= "test";
var emailString ="dot.dot@dot.com";
string sql= "INSERT INTO Table(Id, Subject, Email) VALUES (NEWID(), {subject }, {emailString})";
await _db.Database
.ExecuteSqlCommandAsync(sql);
要证明您可以在Docs
中查看信息答案 1 :(得分:0)
使用参数化查询:
query = INSERT INTO ReportingLogs([UserName],[FirstName])值(@ username,@ firstname)
SqlCommand sqlCommand = new SqlCommand(cmdText,connection); SqlCommand.Parameters.Add(“@ userName”,SqlDbType.VarChar).Value = username
//关闭finally块中的连接或使用using()语句