19

GetSchema我想使用in 方法获取表的列列表ADO.Net,我的代码是:

var dtCols = con.GetSchema("Columns", new[] { "DBName", "TableName" });

我得到一个空的DataTable,有什么问题?

4

4 回答 4

30

您必须为“所有者”限制指定一个参数。

var dtCols = con.GetSchema("Columns", new[] { "DBName", null, "TableName" });
于 2012-06-22T17:06:19.567 回答
1

这两个答案都可以概括为:

dtCols = con.GetSchema("Columns", new[] {con.DataSource, null, "TableName"});

这是假设“TableName”是您想要架构的表的名称。

于 2015-11-16T18:53:38.453 回答
0

我有一个类似的问题,以下工作..

using(SqlCommand command = new SqlCommand(sqlText, con)) {
    var sqlReader = command.ExecuteReader();
    var a = sqlReader.GetColumnSchema();                        
}
于 2017-07-25T09:12:29.327 回答
0

这是我的完整解决方案。

你只需要提供tableNameconnectionString这个方法:

// I took HUGE help from this Microsoft website: - AshishK
// https://docs.microsoft.com/en-us/dotnet/api/system.data.sqlclient.sqlconnection.getschema?view=netframework-4.7.2#System_Data_SqlClient_SqlConnection_GetSchema_System_String_System_String___
public static List<string> GetAllColumnNamesOfATable(string tableName, string connectionString)
{
    var allColumnNames = new List<string>();

    using (var connection = new SqlConnection(connectionString))
    {
        // Connect to the database then retrieve the schema information.  
        connection.Open();

        // You can specify the Catalog, Schema, Table Name, Column Name to get the specified column(s).
        // You can use four restrictions for Column, so you should create a 4 members array.
        String[] columnRestrictions = new String[4];

        // For the array, 0-member represents Catalog; 1-member represents Schema;
        // 2-member represents Table Name; 3-member represents Column Name.
        // Now we specify the Table_Name and Column_Name of the columns what we want to get schema information.
        columnRestrictions[2] = tableName;

        DataTable allColumnsSchemaTable = connection.GetSchema("Columns", columnRestrictions);

        foreach (DataRow row in allColumnsSchemaTable.Rows)
        {
            var columnName = row.Field<string>("COLUMN_NAME");
                
            //You can capture other fields as well, like so:
            var dataType = row.Field<string>("DATA_TYPE");
            var characterMaxLength = row.Field<int?>("CHARACTER_MAXIMUM_LENGTH");

            allColumnNames.Add(columnName);
        }

        connection.Close();
    }

    return allColumnNames;
}
于 2022-03-03T15:12:13.703 回答