如何准确地将正确的数据大小传递到以下行:
objCmd.Parameters.Add(_PNs[i], _DTs[i]).Value = _PVs[i];
它传递了一个 ParameterNames、MySqlDbTypes
数组,但是,我希望也能够传递数据大小...根据传入的 MySqlDbType。
我知道 text、varchar 等...长度会有所不同,但其他一切又如何呢?
附: C#使用最新版本的MySQL,以及最新版本的MySql .Net CONnector
这是我到目前为止所掌握的内容,但它似乎并不像我想象的那么准确。
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;
}
最佳答案
创建两个数组sqlDType和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];
关于c# - 准确设置MySqlCommand参数大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21486397/