如何获取列的数据类型



我使用Northwind示例数据库和ODBC。对于我的C#应用程序,我想将列的数据类型作为type对象(而不是String),因为出于某些原因,我想使用type。

示例(取自Northwind)-表OrderDetails包含列:

OrderID type int(11), ProductID type int(11), UnitPrice type float, etc.

我想要一些类似的东西:

Type dataType = (the data type of OrderID)  

非:string dataType = reader.GetString(dataTypeOrdinal); // I can get this without any problem.

这里是代码片段:(我在代码中也放了一些详细的注释)

var connectionString = Database.ConnectionString;
var command = "SELECT COLUMN_NAME, TABLE_NAME, DATA_TYPE, IS_NULLABLE from INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = '" + _name + "'";
IDataReader reader = null;
reader = _database.Provider.ExecuteReader(command, false);
while (reader.Read())
{
    var columnNameOrdinal = reader.GetOrdinal("column_name");
    var dataTypeOrdinal = reader.GetOrdinal("data_type");
    var columnName = reader.GetString(columnNameOrdinal);
    // till line above everything works fine
    // ---------my problem starts below ---------------
    // I don't need data type as string like this:
    // var dataTypeName = reader.GetString(dataTypeOrdinal);
    // but rather something like: Type dataType = (the data type of column)
    // I tried using reader.GetData(dataTypeOrdinal), but I get
    // System.NotSupportedException: "Specified method is not supported."
}

如有任何帮助和提示,我们将不胜感激。提前Thx。

您可以尝试

var type = reader.GetFieldType(columnNameOrdinal);

或者,如果您想要特定于提供商的类型,您可以使用

var providerSpecificType=    reader.GetProviderSpecificFieldType(int ordinal); 

来自MSDN

Gets an Object that is a representation of the underlying provider-specific field type.

相关内容

  • 没有找到相关文章

最新更新