Bug #102593 Can't use MemoryStream as MySqlParameter.Value
Submitted: 14 Feb 2021 3:25 Modified: 6 Sep 2022 15:17
Reporter: Bradley Grainger (OCA) Email Updates:
Status: Closed Impact on me:
None 
Category:Connector / NET Severity:S4 (Feature request)
Version:8.0.23 OS:Windows (10)
Assigned to: CPU Architecture:Other (x64)

[14 Feb 2021 3:25] Bradley Grainger
Description:
If I have binary data in a MemoryStream object, it would be nice to be able to set MySqlParameter.Value=stream (or command.Parameters.AddWithValue("@data", stream)) in order to insert the data.

However, in Connector/NET, this currently writes the literal string "System.IO.MemoryStream" to the database. Thus, the code "succeeds" but introduces data corruption without warning.

How to repeat:
Run the following C# code:

using var connection = new MySqlConnection(csb.ConnectionString);
connection.Open();

using (var command = connection.CreateCommand())
{
	command.CommandText = @"DROP TABLE IF EXISTS data;
CREATE TABLE data(str TEXT, blb BLOB);
INSERT INTO data(str, blb) VALUES(@str, @blb);";
	using var stream1 = new MemoryStream(new byte[] { 97, 98, 99, 100 });
	command.Parameters.AddWithValue("@str", stream1);
	using var stream2 = new MemoryStream(new byte[] { 97, 98, 99, 100 });
	command.Parameters.AddWithValue("@blb", stream2);
	command.ExecuteNonQuery();
}

using (var command = connection.CreateCommand())
{
	command.CommandText = "SELECT * FROM data;";
	using var reader = command.ExecuteReader();
	reader.Read();

	// expected "abcd"; actual "System.IO.MemoryStream"
	Console.WriteLine(reader.GetString(0));
	Console.WriteLine(reader.GetString(1));
}
[15 Feb 2021 7:28] MySQL Verification Team
Hello Bradley,

Thank you for the reasonable feature request!

regards,
Umesh
[6 Sep 2022 15:17] Christine Cole
Posted by developer:
 
Fixed as of the upcoming MySQL Connector/NET 8.0.31 release, and here's the proposed changelog entry from the documentation team:

Additional validation now checks the MySqlParameter value assignment to
ensure that binary data in a MemoryStream object can be read properly.

Thank you for the bug report.