【问题标题】:getschema("Columns") + return DataType;获取模式(“列”)+返回数据类型;
【发布时间】:2009-11-12 17:54:20
【问题描述】:

我有这个代码

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”列中的字符串值来返回数据类型

 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 或者如何通过在 row["DATA_TYPE"] 中找到的名称获取数据类型??!!

【问题讨论】:

  • 如果 row["DATA_TYPE"] == "int" 你希望 x 的 .NET 类型为 int?如果"varchar(n)" --> string 等等...对吗?
  • 你好,谢谢............是的,我需要什么......请告诉我怎么做?!!
  • 您没有得到答案,因为您没有注册。这里的人想要得到奖励(upvote+accept answer),未注册的用户不能这样做!

标签: c# sql


【解决方案1】:

一种解决方案是创建一个将 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"]);
        }
    }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-09-17
    • 2016-07-01
    • 2018-11-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多