Get the column names of a table and store them in a string or var c# asp.net

前端 未结 6 1061
我寻月下人不归
我寻月下人不归 2021-01-03 16:29

I was wondering how I could get the columns of a database table and store each of them in a string or string array. I have the following code but I believe it does not work.

6条回答
  •  被撕碎了的回忆
    2021-01-03 16:54

    In addition to previous answers here is another way. For me it works faster (not much) than alternatives with DataReader. "WHERE FALSE" tells to bring no data.

    Note that there are no need to iterate through DataTable.Rows as the result DataTable already describes the target table's schema (see the DataTable.Columns), not the schema of the current DataReader results

    DataTable GetDataTableScheme(string tableName)
    {
        var table = new DataTable();
    
        using (var connection = new MySqlConnection(*[ConnectionString]*))
        using (var dataAdapter = new MySqlDataAdapter($"SELECT * FROM {tableName} WHERE FALSE", connection))
        {
            // Adds additional info, like auto-increment
            dataAdapter.MissingSchemaAction = MissingSchemaAction.AddWithKey;
    
            dataAdapter.Fill(table);
        }
    
        return table;
    }
    

提交回复
热议问题