使用ADO.如何获取与DataColumn相关联的数据库表名

本文关键字:关联 DataColumn 数据库 ADO 何获取 获取 使用 | 更新日期: 2023-09-27 18:06:39

假设我有一个列c1的表t1。当我执行'select c1 from t1'时,我可以使用下面的代码片段使用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

使用ADO.如何获取与DataColumn相关联的数据库表名

可以使用

获取表名

schemaTable。表名

以下链接将为您提供所需信息:

https://msdn.microsoft.com/en-us/library/system.data.datatable.tablename (v = vs.110) . aspx

https://msdn.microsoft.com/en-us/library/system.data.datarow.table (v = vs.110) . aspx

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

Select * From INFORMATION_SCHEMA.COLUMNS

你就快搞定了:

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

试试改成:

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