首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >用UniqueIdentifier检索SqlDataReader

用UniqueIdentifier检索SqlDataReader
EN

Stack Overflow用户
提问于 2012-11-15 10:58:50
回答 1查看 2.8K关注 0票数 0

我正在尝试用C#读取SQL中的列类型‘unique标识符’。

代码语言:javascript
复制
SqlCommand myCommand = new SqlCommand();

myCommand.CommandText = "SELECT templatename, subject, bodyhtml, sender, emailTemplateBodyFields.fieldid FROM emailTemplates left join emailtemplaterecipients on emailtemplates.emailtemplateid = emailtemplaterecipients.emailtemplateid left join emailTemplateBodyFields on emailtemplates.emailtemplateid = emailTemplateBodyFields.emailtemplateid WHERE emailtemplates.emailtemplateid = " + selectedEmailTemplateID;

myCommand.Connection = connection;
SqlDataReader myReader = myCommand.ExecuteReader();

while (myReader.Read())
{
    NewTemplateName = myReader.GetString(0);
    NewSubject  = myReader.GetString(1);
    NewBodyHTML = myReader.GetString(2);
    NewRecipients = myReader.GetString(3);
    myRecipientList.Add(NewRecipients);

    Guid tempGUID = myReader.GetGuid(4);
    NewBodyFields = Convert.ToString(tempGUID);
    myBodyList.Add(NewBodyFields);

但是我得到了一个空值异常,数据是空的。

代码语言:javascript
复制
Guid tempGUID = myReader.GetGuid(4);

在Server中运行该语句时,该列没有空值。

请建议如何从本专栏中检索信息。

谢谢。

EN

回答 1

Stack Overflow用户

发布于 2012-11-15 11:08:25

您正在使用LEFT JOINemailTemplateBodyFields。如果该表中不存在相应的记录,则可能导致结果集中的空值,即使对于表中确实存在的记录而言,fieldid从未为空。您可以检查IsDBNull的结果:对于您获得异常的行,您将看到它返回true。

要修复它,要么重新工作查询以确保没有空值,要么准备在调用IsDBNull之前通过检查GetGuid来处理空值。

关于您的代码的两条侧注释:

  • selectedEmailTemplateID来自用户输入吗?如果恶意用户决定设置为"1; DROP TABLE emailTemplates",怎么办?那么您的查询将做什么呢?使用参数。
  • 确保释放你的资源。using关键字使得这非常容易,因此这里没有任何理由不这样做。
票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/13396114

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档