C# Help - C# Community and Information

Part 1: Retrieving Data From SQL Server with C#

December 22nd, 2005 in Data Access by admin

 

Here is a quick and easy sample program in C# to retrieve data from
SQL Server 7.0. There are 4 steps involved in doing this.

a) Create a table 'emp_test' in SQL server with 3 fields calle:d
ecode – int, ename – varchar(20) and ephone – varchar(10).

b) Create a DSN in ODBC called 'test'

c) Save the C# coding.

d) Compile the program using /r:System.Data.dll

using System;
using System.Data.ADO;

public class Test
{
public static void Main()
{
string source = "Provider=MSDASQL; User ID=sa;Initial Catalog=master; Data Source=test";
// 'Provider Name' and 'Initial Catalog' – informations are not mandatory.
string command="SELECT ecode, ename, ephone FROM emp_test\;

ADOCommand mCommand = new ADOCommand();
ADOConnection mConnection=new ADOConnection(source);
try
{
mConnection.Open();
mCommand.ActiveConnection=mConnection;
mCommand.CommandText=command;
ADODataReader mReader;
mCommand.Execute(out mReader);

Console.WriteLine("Code Emp. Name Emp. Phone");
Console.WriteLine("—————————————–");

//Reading Data Line by Line.
while (mReader.Read())
{
Console.WriteLine(mReader.GetInt32(0) + " " + mReader.GetString(1) + " " + mReader.GetString(2));
}

mReader.Close(); //Closing Reader.
mConnection.Close(); //Close Connection.
}
catch(ADOException e)
{
Console.WriteLine("Exception Occured –>> {0}",e.Errors[0].Message);
}
}
}

Most Commented Articles :

Leave a Reply

RSS Feed Follow Us on Twitter!