我想创建一个GUID并将其存储到数据库中。
在C#中,可以使用Guid.NewGuid()来创建一个128位整数的GUID。SQL Server具有uniqueidentifier列,该列保存巨大的十六进制数。
是否有一种好的/首选的方法使C#和SQL Server的GUID相互配合?(即使用Guid.New()创建GUID,然后使用nvarchar或其他字段将其存储在数据库中...或者通过其他方式创建SQL Server期望的形式的十六进制数)
我想创建一个GUID并将其存储到数据库中。
在C#中,可以使用Guid.NewGuid()来创建一个128位整数的GUID。SQL Server具有uniqueidentifier列,该列保存巨大的十六进制数。
是否有一种好的/首选的方法使C#和SQL Server的GUID相互配合?(即使用Guid.New()创建GUID,然后使用nvarchar或其他字段将其存储在数据库中...或者通过其他方式创建SQL Server期望的形式的十六进制数)
下面是一个代码片段,展示了如何使用参数化查询插入GUID:
using(SqlConnection conn = new SqlConnection(connectionString))
{
conn.Open();
using(SqlTransaction trans = conn.BeginTransaction())
using (SqlCommand cmd = conn.CreateCommand())
{
cmd.Transaction = trans;
cmd.CommandText = @"INSERT INTO [MYTABLE] ([GuidValue]) VALUE @guidValue;";
cmd.Parameters.AddWithValue("@guidValue", Guid.NewGuid());
cmd.ExecuteNonQuery();
trans.Commit();
}
}
WHERE
子句。它试图将 C# 中的小写 guid
与大写的 uniqueidentifier
进行比较,而这两者不匹配。 - Edwin StotelerSQL期望GUID作为字符串。以下C#代码返回一个字符串,这个字符串是符合SQL期望的。
"'" + Guid.NewGuid().ToString() + "'"
类似于什么东西
INSERT INTO TABLE (GuidID) VALUE ('4b5e95a7-745a-462f-ae53-709a8583700a')
这是在SQL中应该看起来的样子。
uniqueidentifier
的SQL数据类型(由@TorHaugen在评论中推荐)会被翻译为System.Guid
的C#数据类型,这也是OP所问的。 - Nate AndersonSqlDbType.UniqueIdentifier
,直接将C# Guid值传递给SQL存储过程。public static void StoreGuid(Guid guid)
{
using (var cnx = new SqlConnection("YourDataBaseConnectionString"))
using (var cmd = new SqlCommand {
Connection = cnx,
CommandType = CommandType.StoredProcedure,
CommandText = "StoreGuid",
Parameters = {
new SqlParameter {
ParameterName = "@guid",
<b>SqlDbType = SqlDbType.UniqueIdentifier</b>, // right here
Value = guid
}
}
})
{
cnx.Open();
cmd.ExecuteNonQuery();
}
}
另请参阅:SQL Server 的 {{link1:uniqueidentifier
}}。
将其存储在数据类型为 uniqueidentifier 的字段中。
// Create Instance of Connection and Command Object
SqlConnection myConnection = new SqlConnection(GentEFONRFFConnection);
myConnection.Open();
SqlCommand myCommand = new SqlCommand("your Procedure Name", myConnection);
myCommand.CommandType = CommandType.StoredProcedure;
myCommand.Parameters.Add("@orgid", SqlDbType.UniqueIdentifier).Value = orgid;
myCommand.Parameters.Add("@statid", SqlDbType.UniqueIdentifier).Value = statid;
myCommand.Parameters.Add("@read", SqlDbType.Bit).Value = read;
myCommand.Parameters.Add("@write", SqlDbType.Bit).Value = write;
// Mark the Command as a SPROC
myCommand.ExecuteNonQuery();
myCommand.Dispose();
myConnection.Close();