存储GUID MySQL中从C# [英] Store GUID in MySQL from C#
本文介绍了存储GUID MySQL中从C#的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
试图坚持的GUID从C#(.NET)一个MySQL数据库。 MySQL的列的类型BINARY(16)。如何坚持的GUID,后来从MySQL获得的GUID回任何sugestion?寻找这里的代码的答案: - )
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 ...
数据库模式
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));
}
}
}
这篇关于存储GUID MySQL中从C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文