使用C#获取SQL Server列的数据类型

时间:2020-12-19 16:58:43

I'm not sure what exactly I'm doing wrong, can someone correct it please? I need to determine the type of a retrieved column from a SQL Server database using C#.

我不确定我到底做错了什么,有人可以纠正吗?我需要使用C#从SQL Server数据库中确定检索到的列的类型。

Say, I have this:

说,我有这个:

SqlConnection cn = new SqlConnection("Sql Connection String");
SqlCommand cmd = new SqlCommand("SELECT * FROM [TableName]", cn);
SqlDataReader rdr = cmd.ExecuteReader();

while (rdr.Read())
{
    for (int c = 0; c < rdr.VisibleFieldCount; c++)
    {
        System.Type type = rdr.GetFieldType(c);

        //So can I do this? (Pseudo-code)
        //switch(type)
        //{
        //case string:
        //case int:
        //case DateTime:
        //etc.
        //}
    }
}

1 个解决方案

#1


10  

You can do the following:

您可以执行以下操作:

/* ... code .... */

System.Type type = rdr.GetFieldType(c);

switch (Type.GetTypeCode(type))
{
    case TypeCode.DateTime:
        break;
    case TypeCode.String:
        break;
    default: break;
}

/* ... code .... */

#1


10  

You can do the following:

您可以执行以下操作:

/* ... code .... */

System.Type type = rdr.GetFieldType(c);

switch (Type.GetTypeCode(type))
{
    case TypeCode.DateTime:
        break;
    case TypeCode.String:
        break;
    default: break;
}

/* ... code .... */