一尘不染

从C#将GUID存储在MySQL中

mysql

试图将Guid持久保存在C#(.NET)的MySQL数据库中。MySQL列的类型为BINARY(16)。关于如何保留Guid,然后再从MySQL重新获得Guid的任何建议?在这里寻找代码答案:-)


阅读 509

收藏
2020-05-17

共1个答案

一尘不染

弄清楚了。就是这样 …

数据库架构

CREATE TABLE `test` (                                            
     `id` BINARY(16) NOT NULL,                                      
     PRIMARY KEY  (`id`)                                            
)

string connectionString = string.Format("Server={0};Database={1};Uid={2};pwd={3}", "server", "database", "user", "password");

Guid orgId = Guid.NewGuid();
Guid fromDb = Guid.Empty;

using (MySqlConnection conn = new MySqlConnection(connectionString))
{
    conn.Open();

    using (MySqlCommand cmd = new MySqlCommand("INSERT INTO test (id) VALUES (?id)", conn))
    {
        cmd.Parameters.Add("id", MySqlDbType.Binary).Value = orgId.ToByteArray();
        cmd.ExecuteNonQuery();
    }

    using (MySqlCommand cmd = new MySqlCommand("SELECT id FROM test", conn))
    {
        using (MySqlDataReader r = cmd.ExecuteReader())
        {
            r.Read();
            fromDb = new Guid((byte[])r.GetValue(0));
        }
    }
}
2020-05-17