We can use the SELECT COLUMN_NAME SQL query to get column names of a table in MySQL. Here is the complete syntax:
SELECT column_name FROM information_schema.columns WHERE table_name=@t_name
This query returns all the column names of table 't_name".
Here are the steps to execute this query in ASP.NET.
Step 2: Import the following namespaces:
- using MySql.Data.MySqlClient;
- using MySql.Data;
Step 3: Here is a function to get columnlist by passing tablename and connectionstring in string formats.
- public DataTable ColumnList(string connection, string tablename, bool identity)
- {
- MySqlConnection conn = new MySqlConnection(connection);
- DataTable dt = new DataTable();
- MySqlCommand cmd = new MySqlCommand("select COLUMN_NAME as 'name' from information_schema.columns where table_name=@t_name", conn);
- cmd.Parameters.AddWithValue("@t_name", tablename);
- MySqlDataAdapter da = new MySqlDataAdapter(cmd);
- da.Fill(dt);
- return dt;
- }
Step 4: Now, dt is a DataTable that has columns. You can read column names from there.