繁体   English   中英

使用ADO.Net,如何获取与DataColumn关联的数据库表名称?

[英]Using ADO.Net, how do I get the database table name associated with a DataColumn?

假设我有一个带有列c1的表t1。 当我执行“从t1中选择c1”时,可以使用下面的代码段使用DataTable / DataRow / DataColumn获取结果的元数据

namespace ConsoleApplication1
{
    internal class Program
    {
        private static void Main(string[] args)
        {

            SqlDataAdapter adapter;
            DataSet dataset = new DataSet();
            using (SqlConnection connection
                = new SqlConnection(@"Persist Security Info=False;Trusted_Connection=True;"))
            {

                SqlCommand command = new SqlCommand(
                    @"SELECT c1 from t1 where 1 = 0;", connection);
                connection.Open();

                SqlDataReader reader = command.ExecuteReader();
                DataTable schemaTable = reader.GetSchemaTable();
                Console.WriteLine(reader.GetName(0)); //Name of column
                foreach (DataRow row in schemaTable.Rows)
                {
                    //Console.WriteLine(row["TableName"]);
                    foreach (DataColumn column in schemaTable.Columns)
                    {
                        Console.WriteLine(String.Format("{0} = {1}",
                            column.ColumnName, row[column]));

                    }
                }


            }
        }
    }
}

但是为BaseTableName返回的值为空白。 是否有其他可用方法来获取与列“ c1”关联的表“ t1”?

这是上面代码的输出:

ColumnName = c1
ColumnOrdinal = 0
ColumnSize = 100
NumericPrecision = 255
NumericScale = 255
IsUnique = False
IsKey = 
BaseServerName = 
BaseCatalogName = 
BaseColumnName = c1
BaseSchemaName = 
BaseTableName = 
DataType = System.String
AllowDBNull = True
ProviderType = 3
IsAliased = 
IsExpression = 
IsIdentity = False
IsAutoIncrement = False
IsRowVersion = False
IsHidden = 
IsLong = False
IsReadOnly = False
ProviderSpecificDataType = System.Data.SqlTypes.SqlString
DataTypeName = char
XmlSchemaCollectionDatabase = 
XmlSchemaCollectionOwningSchema = 
XmlSchemaCollectionName = 
UdtAssemblyQualifiedName = 
NonVersionedProviderType = 3
IsColumnSet = False

尝试以下操作以获取所有表/列信息

Select * From INFORMATION_SCHEMA.COLUMNS

您几乎可以在这里找到它:

//Console.WriteLine(row["table_name"]);

尝试将其更改为:

Console.WriteLine(row["TableName"]);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM