Question

How can I accurately pass in the proper data size to the following line:

objCmd.Parameters.Add(_PNs[i], _DTs[i]).Value = _PVs[i];

It is passed an array of ParameterNames, MySqlDbTypes, however, I would like to be able to pass the in the data size as well... according to the MySqlDbType passed in.

I know text, varchar, etc... lengths will vary, but what about everything else?

p.s. C# using the latest version of MySQL, and the latest version of the MySql .Net COnnector

Here's what I have so far, but it does not seem to be nearly as accurate as I assume that it should be.

objCmd.Parameters.Add(_PNs[i], _DTs[i], _EstimatedSize(_PVs[i])).Value = _PVs[i];

// this method is pretty dumb but we want it to be fast.
internal int _EstimatedSize(object _val)
{
    if (_val == null || _val == DBNull.Value)
        return 4; // size of NULL
    if (_val is byte[])
        return (_val as byte[]).Length;
    if (_val is string)
        return (_val as string).Length * 4; // account for UTF-8
    if (_val is decimal || _val is float)
        return 64;
    if (_val is bool)
        return 1;
    return 32;
}
Was it helpful?

Solution

Create two array sqlDType and sqlSize

SqlDbType[] sqlDType = new SqlDbType[] {SqlDbType.Int, SqlDbType.Float, SqlDbType.SmallInt, SqlDbType.TinyInt};
int[] sqlSize = new int[] { 4, 8, 2, 1 };
SqlDbType type = SqlDbType.Float;
int iIndex = Array.IndexOf(sqlDType, type);
int iSize = -1;
if (iIndex > -1)
    iSize = sqlSize[iIndex];
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top