我使用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提前。
答案 0 :(得分:1)
你可以尝试
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.