简体   繁体   English

C# Mysql 插入blob

[英]C# Mysql insert blob

i've been trying to insert byte value into Mysql.我一直在尝试将字节值插入 Mysql。 But with no success.但没有成功。 It insert the length of the array instead of the item attributes.它插入数组的长度而不是项目属性。 Then i need help how do i convert it from blob to readable format然后我需要帮助我如何将它从 blob 转换为可读格式

string itemsQuery = "INSERT INTO `player_items` (`player_id`, `item_id`, `count`, `attributes`) VALUES ";
using (MemoryStream memoryStream = new MemoryStream())
{
    BinaryFormatter binaryFormatter = new BinaryFormatter();
    binaryFormatter.Serialize(memoryStream, ItemAttributes);
    byte[] mStream = memoryStream.ToArray();
    string newQuery = string.Format("{0} ({1},{2},{3},{4});", itemsQuery, 1, 1, 1, mStream);
    ExecuteNonQuery(newQuery);
}

string nquery = "SELECT `attributes` FROM `player_items` WHERE " + 1;
using (MemoryStream memoryStream = new MemoryStream(Convert.FromBase64String(nquery))
{
    BinaryFormatter binaryFormatter = new BinaryFormatter();
    binaryFormatter.Deserialize(memoryStream);
}

public int ExecuteNonQuery(string commandText)
{
    int affectedRows = 0;
    using (var connection = mySqlConnection)
    {
        using (var command = new MySqlCommand(commandText, connection))
        {
            affectedRows = command.ExecuteNonQuery();
        }
    }
    return affectedRows;
}

在此处输入图像描述

My suggestion it to use parameters instead of string concatenation and let the engine do the serialization for you:我的建议是使用参数而不是字符串连接,让引擎为您进行序列化:

string itemsQuery = "INSERT INTO `player_items` (`player_id`, `item_id`, `count`, `attributes`) VALUES (@player_id, @item_id, @count, @attributes)";
MySqlParameter[] parameters = {
    new MySqlParameter("player_id",1),
    new MySqlParameter("item_id",1),
    new MySqlParameter("count",1),
    new MySqlParameter("attributes",MySqlDbType.Blob)
    };
parameters[3].Value = ItemAttributes;
ExecuteNonQuery(itemsQuery, parameters);

public int ExecuteNonQuery(string commandText, params MySqlParameter[] parameters)
{
    int affectedRows = 0;
    using (var connection = mySqlConnection)
    {
        using (var command = new MySqlCommand(commandText, connection))
        {
            command.Parameters.AddRange(parameters);
            affectedRows = command.ExecuteNonQuery();
        }
    }
    return affectedRows;
}

I also notice you seem to be re-using mySqlConnection which is a bad idea.我还注意到您似乎在重新使用mySqlConnection这是一个坏主意。 Connections are pooled in .NET, so they are relatively cheap to create.连接集中在 .NET 中,因此创建起来相对便宜。 The best practice is to create a new MySqlConnection in the using block rather then re-using an existing one.最佳实践是在using块中创建一个新的MySqlConnection ,而不是重新使用现有的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM