Class DBTypeConversion
{
private static String[,] DBTypeConversionKey = new String[,]
{
{"BigInt","System.Int64"},
{"Binary","System.Byte[]"},
{"Bit","System.Boolean"},
{"Char","System.String"},
{"DateTime","System.DateTime"},
{"Decimal","System.Decimal"},
{"Float","System.Double"},
{"Image","System.Byte[]"},
{"Int","System.Int32"},
{"Money","System.Decimal"},
{"NChar","System.String"},
{"NText","System.String"},
{"NVarChar","System.String"},
{"Real","System.Single"},
{"SmallDateTime","System.DateTime"},
{"SmallInt","System.Int16"},
{"SmallMoney","System.Decimal"},
{"Text","System.String"},
{"Timestamp","System.DateTime"},
{"TinyInt","System.Byte"},
{"UniqueIdentifer","System.Guid"},
{"VarBinary","System.Byte[]"},
{"VarChar","System.String"},
{"Variant","System.Object"}
};
public static SqlDbType SystemTypeToDbType(System.Type sourceType)
{
SqlDbType result;
String SystemType = sourceType.ToString();
String DBType = String.Empty;
int keyCount = DBTypeConversionKey.GetLength(0);
for(int i=0;i<keyCount;i++)
{
if(DBTypeConversionKey[i,1].Equals(SystemType)) DBType = DBTypeConversionKey[i,0];
}
if (DBType==String.Empty) DBType = "Variant";
result = (SqlDbType)Enum.Parse(typeof(SqlDbType), DBType);
return result;
}
public static Type DbTypeToSystemType(SqlDbType sourceType)
{
Type result;
String SystemType = String.Empty;
String DBType = sourceType.ToString();
int keyCount = DBTypeConversionKey.GetLength(0);
for(int i=0;i<keyCount;i++)
{
if(DBTypeConversionKey[i,0].Equals(DBType)) SystemType = DBTypeConversionKey[i,1];
}
if (SystemType==String.Empty) SystemType = "System.Object";
result = Type.GetType(SystemType);
return result;
}
http://social.msdn.microsoft.com/Forums/en/winforms/thread/c6f3ab91-2198-402a-9a18-66ce442333a6 希望这有助于更好地阐明。
http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlparametercollection.addwithvalue.aspx
我没有使用SqlCommand。我的类型是'IDbCommand'类型。而在IDbCommand中,您无法执行command.Parameters.AddWithValue(...);只有command.Parameters.Add()是因为command.Parameters是IDataParameterCollection类型。 – michael 2011-06-14 13:56:44
NB有点正确。您不需要明确设置DbType,只需将值传入。但是,您也是正确的。 IDbCommand.Parameters没有AddWithValue方法。看到我的回答如下... – 2011-06-14 14:06:52
我的不好!接口没有指定这种区别。我知道SqlCommand和OracleCommand对象都不需要定义的DbType。但是......我不知道可能需要它们的其他实现。我已经用相应的方法更新了我的答案。 – 2011-06-14 14:19:39