簡體   English   中英

C# guid 和 SQL uniqueidentifier

[英]C# guid and SQL uniqueidentifier

我想創建一個 GUID 並將其存儲在數據庫中。

在 C# 中,可以使用 Guid.NewGuid() 創建 guid。 這將創建一個 128 位整數。 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();
        }
    }

SQL 期望 GUID 作為字符串。 C# 中的以下內容返回 Sql 期望的字符串。

"'" + Guid.NewGuid().ToString() + "'"

就像是

INSERT INTO TABLE (GuidID) VALUE ('4b5e95a7-745a-462f-ae53-709a8583700a')

是它在 SQL 中的樣子。

您可以通過指定SqlDbType .UniqueIdentifier將 C# Guid 值直接傳遞給 SQL 存儲過程。

您的方法可能如下所示(前提是您的唯一參數是 Guid):

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",
                SqlDbType = SqlDbType.UniqueIdentifier, // right here
                Value = guid
            }
        }
    })
    {
        cnx.Open();
        cmd.ExecuteNonQuery();
    }
}

另請參閱:SQL Server 的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();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM