Ok I have a GUID f5cc4100-f1b4-4af6-9e9e-224b0eb74166
and I am inserting it to MySQL database using the ADO .NET Connector.
I can do it in two ways:
1) Feed byte array to .NET Connector
string query = "insert into test (pk_id) values (@id)";
using (var c = new MySqlCommand(query, conn))
{
c.Parameters.AddWithValue("@id", new Guid("f5cc4100-f1b4-4af6-9e9e-224b0eb74166").ToByteArray());
c.ExecuteNonQuery();
}
2) Rely on MySQL standard function to convert hexadecimal to binary string.
string query = "insert into test (pk_id) values (UNHEX(@id))";
using (var c = new MySqlCommand(query, conn))
{
c.Parameters.AddWithValue("@id", "f5cc4100-f1b4-4af6-9e9e-224b0eb74166".Replace("-", "");
c.ExecuteNonQuery();
}
The problem I face is the two above methods inserts the same guid in slightly different character order.
If I am selecting back the inserted guid like this:
string query = "select PK_id from test";
using (var c = new MySqlCommand(query, conn))
{
using (var r = c.ExecuteReader())
{
while (r.Read())
{
var k = new Guid((byte[])r[0]);
}
}
}
I get f5cc4100-f1b4-4af6-9e9e-224b0eb74166
and 0041ccf5-b4f1-f64a-9e9e-224b0eb74166
back. But if I am reading like this:
string query = "select hex(PK_id) from test";
using (var c = new MySqlCommand(query, conn))
{
using (var r = c.ExecuteReader())
{
while (r.Read())
{
var k = new Guid((string)r[0]);
}
}
}
I get 0041ccf5-b4f1-f64a-9e9e-224b0eb74166
and f5cc4100-f1b4-4af6-9e9e-224b0eb74166
.
In short, if I am inserting the GUID as bytearrays, then I need to read them as such and cast as byte arrays to get the right GUID. And if I am inserting the GUID as UNHEX
of the hexadecimal guid string, then I need to read from db using its equivalent HEX
function.
Why are writing and reading different with the above two methods?
What would be the more appropriate way of handling GUIDs between the two?