Reputation: 465
i've been trying to insert byte value into 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
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;
}
Upvotes: 0
Views: 991
Reputation: 152556
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. Connections are pooled in .NET, so they are relatively cheap to create. The best practice is to create a new MySqlConnection
in the using
block rather then re-using an existing one.
Upvotes: 1