【问题标题】:Retrieving UniqueIdentifier with SqlDataReader使用 SqlDataReader 检索 UniqueIdentifier
【发布时间】:2012-11-15 10:58:50
【问题描述】:

我正在尝试使用 C# 在 SQL 中读取列类型“唯一标识符”

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

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

Guid tempGUID = myReader.GetGuid(4);

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

请告知如何从该列中检索信息。

谢谢。

【问题讨论】:

    标签: c# sql sql-server guid uniqueidentifier


    【解决方案1】:

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

    要解决这个问题,要么重新编写查询以确保没有得到空值,要么在调用 GetGuid 之前通过检查 IsDBNull 来准备处理空值。

    您的代码上有两个侧边:

    • selectedEmailTemplateID 是否来自用户输入?如果恶意用户决定设置为"1; DROP TABLE emailTemplates" 怎么办?然后您的查询会做什么?使用参数。
    • 确保释放您的资源。 using 关键字让这一切变得如此简单,真的没有理由不这样做。

    【讨论】:

    • 感谢 if (!myReader.IsDBNull(4)) 确实删除了错误,但我不明白为什么它说有空值,当在 sql server 中运行它提供数据时。不,不是来自用户输入,来自选择。这只会在内部使用
    • @Wayneio 也许是一个愚蠢的问题,但是您是否在同一数据库上运行 exact 相同的查询(包括相同的过滤器),并且您是否正在检查结果集?
    • 是的,使用相同的 emailtemplateid 复制和粘贴。我认为这可能是因为该列是“唯一标识符”,因为我对存储为字符串的其他行没有问题
    • 我大量使用uniqueidentifier,而Entity Framework 没有问题,它在幕后使用SqlDataReader,所以我怀疑这是你问题的根源。但是,如果您愿意,测试应该相当容易:在测试数据库上,更改fieldid 的类型,更改您的代码以调用GetString,然后看看会发生什么。
    猜你喜欢
    • 2013-07-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-14
    • 1970-01-01
    • 2011-10-20
    相关资源
    最近更新 更多