Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Store GUID in MySQL from C#

Tags:

c#

mysql

Trying to persist Guid's in a MySQL db from C# (.NET). MySQL column is of type BINARY(16). Any sugestion on how to persist the guid and later get the guid back to from MySQL? Looking for a code answer here :-)

like image 435
Tim Skauge Avatar asked Apr 12 '09 17:04

Tim Skauge


2 Answers

Figured it out. Here's how ...

Database schema

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

Code

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));
        }
    }
}
like image 67
Tim Skauge Avatar answered Oct 25 '22 07:10

Tim Skauge


Apparently, the GetGuid() method in MySQL .NET Connector v5.2.6+ should be fixed so you can use this example.

like image 41
Magnus Johansson Avatar answered Oct 25 '22 06:10

Magnus Johansson