Home > Software design >  How to view data from a database in cmd
How to view data from a database in cmd

Time:11-26

Good morning, I'm doing a job where I have to show some information from a database in cmd, I search the internet and only find in Tables DataGrid do not understand how I will do, I have the following code:

public class atm
{
    public static void Main()
    {
        string connectionString;
        SqlConnection cnn;
        connectionString = @"Data Source=MAD-PC-023;Database=atmbd;Trusted_Connection=True;";
        cnn = new SqlConnection(connectionString);
        try
    {
            using (SqlCommand cmd = cnn.CreateCommand())
            {
                cnn.Open();
                Console.WriteLine("Is working");

                var sqlQuery = "SELECT FirstName FROM tblATM";
                using (SqlDataAdapter da = new SqlDataAdapter(sqlQuery, cnn))
                {
                    using (DataTable dt = new DataTable())
                    {
                        da.Fill(dt);
                        Console.WriteLine(dt);
                    }
                }
            }
        }
        catch (SqlException erro)
    {
        Console.WriteLine("Is not working"   erro);
    }
        finally
        {
            cnn.Close();
        }
    }
}

When I open it says it's working, then I think the connection is working but it doesn't show the database data I'm asking for. If anyone knows how to help me, i'd appreciate it.

CodePudding user response:

A DataTable is overkill, consider the following to loop through the records.

internal class Program
{
    static void Main(string[] args)
    {
        using (var cn = new SqlConnection("Data Source=MAD-PC-023;Database=atmbd;Trusted_Connection=True;"))
        {
            using (var cmd = new SqlCommand() { Connection = cn, CommandText = "SELECT FirstName FROM tblATM" })
            {
                cn.Open();
                var reader = cmd.ExecuteReader();
                while (reader.Read())
                {
                    Console.WriteLine(reader.GetString(0));
                }
            }
        }

        Console.ReadLine();
    }
}

With last name

using (var cn = new SqlConnection("Data Source=MAD-PC-023;Database=atmbd;Trusted_Connection=True;"))
{
    using (var cmd = new SqlCommand() { Connection = cn, CommandText = "SELECT FirstName,LastName FROM tblATM" })
    {
        cn.Open();
        var reader = cmd.ExecuteReader();
        while (reader.Read())
        {
            Console.WriteLine($"{reader.GetString(0)} {reader.GetString(1)}");
        }
    }
}

CodePudding user response:

You can use dapper to connect and query data from a database connection. The below link is the official documentation of dapper https://www.learndapper.com/ here you can find sample code also.

  • Related