Bug #32094 Size property on string parameter throws an exception
Submitted: 5 Nov 2007 1:32 Modified: 13 Nov 2007 11:42
Reporter: John Crouch Email Updates:
Status: Closed Impact on me:
None 
Category:Connector / NET Severity:S3 (Non-critical)
Version:5.1.3 OS:Any
Assigned to: CPU Architecture:Any
Tags: MySqlParameter

[5 Nov 2007 1:32] John Crouch
Description:
When the Size property of a MySqlParameter is greater than the length of the string contained in the Value property you will get the following exception:

Index and length must refer to a location within the string.
Parameter name: length

This is caused by the Substring call in the MySqlString class within the connector.

string v = val.ToString();
if (length > 0)
    v = v.Substring(0, length);

In my example below, the string is only 3 long and he Size parameter is 50, so the Substring method throws the exception.

How to repeat:
MySqlConnection MyConnection = new MySqlConnection( "Database=dbname;Data Source=localhost;User Id=user;Password=password;" );
MySqlParameter NewParam = new MySqlParameter("P1", MySql.Data.MySqlClient.MySqlDbType.VarChar);
NewParam.Value = "dog";
NewParam.Size = 50;
MySqlCommand MyCommand = new MySqlCommand("UPDATE TableName SET FieldName = ?P1 WHERE ID = 999;", MyConnection);
MyCommand.Parameters.Add( NewParam );
MyConnection.Open();
MyCommand.ExecuteNonQuery();
MyConnection.Close();

Suggested fix:
This code should be fixed by only using the Substring method to truncate the string if its length is greater than Size property value.
[5 Nov 2007 17:10] Bugs System
A patch for this bug has been committed. After review, it may
be pushed to the relevant source trees for release in the next
version. You can access the patch from:

  http://lists.mysql.com/commits/37112
[5 Nov 2007 17:11] Bugs System
A patch for this bug has been committed. After review, it may
be pushed to the relevant source trees for release in the next
version. You can access the patch from:

  http://lists.mysql.com/commits/37113
[5 Nov 2007 17:12] Reggie Burnett
Fixed in 5.0.9 and 5.1.4
[5 Nov 2007 18:05] Bugs System
A patch for this bug has been committed. After review, it may
be pushed to the relevant source trees for release in the next
version. You can access the patch from:

  http://lists.mysql.com/commits/37115
[5 Nov 2007 18:22] Reggie Burnett
Also fixed in 1.0.11
[13 Nov 2007 11:42] MC Brown
A note has been added to the 1.0.11, 5.0.9 and 5.1.4 changelogs: 

        Setting the size of a string parameter after the value could
        cause an exception.