从C#将GUID存储在MySQL中
试图将Guid持久保存在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));
}
}
}
以上是 从C#将GUID存储在MySQL中 的全部内容, 来源链接: utcz.com/qa/416335.html