C# program to print column names of a MySQL Table

Here, we will learn how to print column names of a MySQL Table using C# program? By Nidhi Last updated : April 04, 2023

Problem Statement

In this program, we will connect to the MySQL database and get the columns of the "employee" table and then print them on the console screen.

C# code to print column names of a MySQL Table

The source code to print the column name of a specified MySql database table is given below. The given program is compiled and executed successfully.

// C# program to print the column names of a 
// specified MySql database table.

using MySql.Data.MySqlClient;
using System;

class Program {
  static void Main(string[] args) {
    // Connection String to connect with MySQL database.
    string connString = "server=localhost;userid=root;password=root;database=Sample_DB";
    MySqlConnection conn = new MySqlConnection(connString);


    MySqlCommand cmd = new MySqlCommand("SELECT * FROM employee", conn);

    MySqlDataReader reader;

    reader = cmd.ExecuteReader();

    Console.WriteLine("Employee table columns: ");
    Console.WriteLine("\t" + reader.GetName(0));
    Console.WriteLine("\t" + reader.GetName(1));
    Console.WriteLine("\t" + reader.GetName(2));



Employee table columns:
Press any key to continue . . .


In the above program, we imported a namespace MySql.Data.MySqlClient to establish the connection with the MySql database. Then we created a class Program that contains the Main() method.

The Main() method is the entry point for the program. In the Main() method, we created a connection string variable ConnString that contains the database connectivity credentials. After that, we established the connection to the MySql database using MySqlConnection class and then get the column names using ExecuteReader() and GetName() methods of MySqlDataReader class and then print them on the console screen.

C# Database Programs »

Comments and Discussions!

Load comments ↻

Copyright © 2024 www.includehelp.com. All rights reserved.