C# program to get records from a MySQL table

Here, we will learn how to get records from 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 employee records of the employee table then print them on the console screen.

C# code to get and print the records of a MySQL table

The source code to get and print the records of a MySQL table is given below. The given program is compiled and executed successfully.

// C# program to print the column values 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);

    conn.Open();

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

    MySqlDataReader reader;

    reader = cmd.ExecuteReader();

    while (reader.Read()) {
      Console.WriteLine(reader.GetInt32(0) + " " + reader.GetString(1) + " " + reader.GetUInt32(2));
    }

    conn.Close();
  }
}

Output

101 Sumit Kumar 63200
102 Vijay 25000
Press any key to continue . . .

Explanation

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 employee records using MySqlDataReader class. Here, we used Read() method to record one by one and we used GetInt32(), GetString() methods to read column values and print records on the console screen.

C# Database Programs »




Comments and Discussions!

Load comments ↻





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