我有一个小程序来“下载”数据库表到Excel。
我想将列类型添加到第二行,然后使用以下函数进行尝试。它工作得很好,但是GetDataTypeName(i)只返回int, nvarchar,但我需要如下所示的完整类型规范
nvarchar(255), decimal(19, 8)还有其他函数可以从数据库中获取此信息吗?
SqlDataReader dataReader = command.ExecuteReader();
// adds the names and the types if the table has no values
if (!dataReader.HasRows || !withValues)
{
for (int i = 0; i < dataReader.FieldCount; i++)
{
names.Add(dataReader.GetName(i));
types.Add(dataReader.GetDataTypeName(i));
}
}发布于 2016-10-26 12:53:38
这种信息可以通过调用GetSchemaTable获得。它返回一个DataTable,其中对查询返回的每个列都有一行。此表的每一列描述元数据相对于查询字段提取的特定信息。
例如
SqlDataReader dataReader = command.ExecuteReader();
if (!dataReader.HasRows || !withValues)
{
DataTable dt = dataReader.GetSchemaTable();
foreach(DataRow row in dt.Rows)
{
Console.WriteLine("ColumnName: " + row.Field<string>("ColumnName"));
Console.WriteLine("NET Type: " + row.Field<string>("DataTypeName"));
Console.WriteLine("Size: " + row.Field<int>("ColumnSize"));
}
}GetSchemaTable返回大量关于表/查询的信息,但其中许多字段设置为null。我不确定这是提供者的限制还是空的,因为在调用的上下文中,它们没有任何意义。无论如何,在访问这些值时使用防御性编程(if !(value == DBNull.Value) )
发布于 2016-10-26 12:55:11
请使用TableSchema方法获取列的所有细节。
SqlDataReader reader= command.ExecuteReader();
using (var schemaTable = reader.GetSchemaTable())
{
foreach (DataRow row in schemaTable.Rows)
{
string ColumnName= row.Field<string>("ColumnName");
string DataTypeName= row.Field<string>("DataTypeName");
short NumericPrecision= row.Field<short>("NumericPrecision");
short NumericScale= row.Field<short>("NumericScale");
int ColumnSize= row.Field<int>("ColumnSize");
Console.WriteLine("Column: {0} Type: {1} Precision: {2} Scale: {3} ColumnSize {4}",
ColumnName, DataTypeName, NumericPrecision, scale,ColumnSize);
}
}谢谢。
https://stackoverflow.com/questions/40262409
复制相似问题