getschema(“Columns”)+ return DataType;

时间:2009-11-12 08:18:11

标签: c# sql

我有这个代码

using (SqlConnection conn = new SqlConnection(ConnectionString))
                    {
                        conn.Open();
                        DataTable Databases = conn.GetSchema("Databases");
                        DataTable Tables = conn.GetSchema("Tables");
                        DataTable Columns = conn.GetSchema("Columns");
                        conn.close();
                     }

我需要通过读取“DATA_TYPE”列中的字符串值来返回datattype

 foreach (DataRow row in Columns.Rows)
                if (row["TABLE_NAME"].ToString() == tableName)
                {
                    if (fName == row["COLUMN_NAME"].ToString())
                    {
                      //return Datatype 
                      var x = row["DATA_TYPE"];
                    }
                }

//// if(row [“DATA_TYPE”] ==“int”)我如何通过DataType(Int)设置var x 或者如何在行[“DATA_TYPE”] ?? !!

中找到按名称获取的数据类型

1 个答案:

答案 0 :(得分:4)

解决方案是创建一个将sql类型映射到.net类型的字典:

Dictionary<string, Type> sqlToNetTypes;

并使用“DATA_TYPE”列及其.NET等效项中的所有可能类型填充它:

sqlToNetTypes.Add("int", typeof(int));
sqlToNetTypes.Add("varchar", typeof(sting));
sqlToNetTypes.Add("datetime", typeof(DateTime));
sqlToNetTypes.Add("bit", typeof(bool));
sqlToNetTypes.Add("numeric", typeof(float));//or double or decimal as you like...
...

然后用辅助方法:

Type GetNETType(string sqlType)
{
    if(sqlToNetTypes.ContainsKey(sqlType))
    {
        return sqlToNetTypes[sqlType];
    }else
    {
        return typeof(object); //generic type
    }
}

并像这样使用它:

foreach (DataRow row in Columns.Rows)
    if (row["TABLE_NAME"].ToString() == tableName)
    {
        if (fName == row["COLUMN_NAME"].ToString())
        {
            //return Datatype 
            var x = GetNETType(row["DATA_TYPE"]);
        }
    }