从C#在MySQL中存储GUID

前端之家收集整理的这篇文章主要介绍了从C#在MySQL中存储GUID前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
试图将Guid’s保存在来自C#(.NET)的 MySQL数据库中. MySQL列的类型为BINARY(16).有关如何坚持guid以及后来从MysqL获取guid的任何消息?在这里寻找代码答案:-)

解决方法

弄清楚了.这是如何做 …

数据库架构

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));
        }
    }
}
原文链接:https://www.f2er.com/csharp/97593.html

猜你在找的C#相关文章