Home

Simple Data Display

 

Description

When dealing with a database in a console application, you may want to display the records on a DOS window. To do this, you can use a DataSet object.

The DataSet class allows you to access any type of information from a table. These include table's object name, the columns (and their properties), and the records. This means that you should be able to locate a record, retrieve its value, and pass it to the Console.Write() or the Console.WriteLine() methods. Probably the only real problem is to make sure your DataSet object can get the necessary records. The records could come from a database (Microsoft SQL Server, Oracle, Microsoft Access, Paradox, etc).

Here is an example of displaying data on a console from the records of a Microsoft SQL Server table:

using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
using System.Data.SqlClient;

public class Program
{
    static int Main()
    {
        SqlConnection conDatabase =
            new SqlConnection("Data Source=(local);Database='bcr1';" +
                "Integrated Security=true");
        SqlCommand cmdDatabase =
        new SqlCommand("SELECT * FROM dbo.Employees;", conDatabase);

        DataSet dsEmployees = new DataSet("EmployeesSet");
        SqlDataAdapter sda = new SqlDataAdapter();
        sda.SelectCommand = cmdDatabase;
        sda.Fill(dsEmployees);

        DataRow recEmployee = dsEmployees.Tables[0].Rows[0];

        Console.WriteLine("First Name: {0}", (String)recEmployee["FirstName"]);
        Console.WriteLine("Last Name:  {0}", (String)recEmployee["LastName"]);

        conDatabase.Close();

        return 0;
    }
}
 

Home Copyright © 2007-2012 FunctionX