【问题标题】:Error in VB.Net -- Conversion failed when converting from a character string to uniqueidentifierVB.Net 中的错误——从字符串转换为唯一标识符时转换失败
【发布时间】:2013-11-11 15:26:12
【问题描述】:

我收到“从字符串转换为唯一标识符时转换失败。”

我在 VB 端使用字符串,在数据库端使用 GUID.....

是否有我可以在 VB 端使用的等效字段,它可以很好地与 Sql Server 中的“唯一标识符”数据类型一起使用

【问题讨论】:

  • uniqueidentifierGUID。除此之外,不要连接查询,而是使用 sql 参数来防止转换或本地化错误,更重要的是防止 sql 注入。
  • 表列为GUID时,空字符串parmList.Add(String.Empty)如何处理?

标签: sql-server vb.net datatable uniqueidentifier


【解决方案1】:

如果您已经将值作为字符串,并且由于您是手动编写 SQL,您可以像这样CONVERT 它:

strSql.Append("INSERT INTO tableName ")
strSql.Append("(GUID, ParentObsSetGUID, ChildObsSetGUID, ChildObsItemGUID) ")
strSql.Append(String.Format("VALUES (CONVERT(uniqueidentifier, '{0}'), CONVERT(uniqueidentifier, '{1}'), CONVERT(uniqueidentifier, '{2}'), CONVERT(uniqueidentifier, '{3}'))", parmList.ToArray))

编辑:如果您有一个空字符串并且需要一个新的 Guid,请执行以下操作:

parmList.Add(Guid.NewGuid().ToString())

而不是

parmList.Add(String.Empty)

如果您希望在 GUID 列中插入 NULL,则需要将代码的最后一位更改为:

parmList.Add(dtNewGUID.Rows(0).Item(0).ToString)
parmList.Add(dtResultParentGUID.Rows(0).Item(0).ToString)
parmList.Add(dtResultChildGUID.Rows(0).Item(0).ToString)
// remove the line with the empty string parameter
strSql.Append("INSERT INTO tableName ")
strSql.Append("(GUID, ParentObsSetGUID, ChildObsSetGUID, ChildObsItemGUID) ")
strSql.Append(String.Format("VALUES (CONVERT(uniqueidentifier, '{0}'), CONVERT(uniqueidentifier, '{1}'),
CONVERT(uniqueidentifier, '{2}'), NULL)", parmList.ToArray))
// Note the change to the last line. '{3}' becomes NULL.
// Make sure you remove the single quotes

注意:您的代码(以及此答案)容易受到 SQL 注入攻击,但这是另一回事。至少有了这个答案,您就知道如何将字符串转换为uniqueidentifier

【讨论】:

  • 以下仍然给我同样的错误: INSERT INTO aic_obs_set_obs_set_obs_item_xref (GUID, ParentObsSetGUID, ChildObsSetGUID, ChildObsItemGUID) VALUES (CONVERT(uniqueidentifier, 'a1771622-6cd6-49f7-8b26-6befaf556e'), uniqueidentifier, '4746da06-e830-42a0-9761-ce60a62ea4d1'), CONVERT(uniqueidentifier, '633ce901-1d4d-479c-b295-232fe7b53295'), CONVERT(uniqueidentifier, ''))
猜你喜欢
  • 2013-02-12
  • 1970-01-01
  • 2011-12-15
  • 2013-10-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多