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 :-)
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));
}
}
}
Apparently, the GetGuid()
method in MySQL .NET Connector v5.2.6+ should be fixed so you can use this example.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With