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

前端 未结 6 1093
我寻月下人不归
我寻月下人不归 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 17:07

    I will show you how to do it with MySQL database table. Similar code structure can be used for your case as well. Basically you should run "DESC table_name" query. Then you have a table description as a resulting table. You can read dataReader and retrieve whatever information filed from the Table Description. In this example I retrieve column names of the specific DB table. Hope this will save someones time. :) Happy coding!

     var tableDesc = "DESC table_name";
    
            try
            {
                Mclient.MySqlCommand tableDescCmd = new Mclient.MySqlCommand(tableDesc, mCon);
                Mclient.MySqlDataReader tableDescDR = tableDescCmd.ExecuteReader();
    
                while (tableDescDR.Read())
                {
    
                    searchFields.Items.Add(tableDescDR.GetFieldValue(tableDescDR.GetOrdinal("Field")));
                }
    
                tableDescDR.Close();
            }
            catch (Exception ex)
            {
                MessageBox.Show("Could not retrieve DB Table fields.\n" + ex.Message);
            }
    

提交回复
热议问题