Tuesday, 18 December 2012 16:54

Database connection implementation using function & xml file

Written by 
Rate this item
(0 votes)

It's a good idea to use a class say gateway where all
database access codes will be written.in this gateway class
you will implement db connection as follows -

first create another class -

public class DBConnector
{
private string connectionString = null;
public DBConnector()
{
XmlTextReader reader = new XmlTextReader("LandscapeConfiguration.xml");
string nodeName = "";
while (reader.Read())
{
switch (reader.NodeType)
{
case XmlNodeType.Element:
nodeName = reader.Name;break;
case XmlNodeType.Text:
switch (nodeName)
{case "connectionstring":
connectionString = reader.Value;
break;}
break;
case XmlNodeType.EndElement:
break;
}}}

public SqlConnection Connect
{
get { return new SqlConnection(connectionString); }
}}

now in the gateway class constructor function initiate the connection -
DBConnector dbConnector = new DBConnector();
SqlConnection connection = dbConnector.Connect;
connection.Open();

now in the gateway class your db access method will be like that-

public SqlDataReader GetAllDepartmentInformation()
{
string selectQueryString = @"SELECT * FROM t_Department";
SqlCommand selectAllDepartmentCommand = new SqlCommand(selectQueryString,connection);
SqlDataReader reader = selectAllDepartmentCommand.ExecuteReader();
return reader;
}

and in your form/aspx page's code behind page access db data by-

DepartmentGateway department=new DepartmentGateway();
List<Department> departments = department.GetAllDepartmentInformation();

Read 2884 times
Super User

Email This email address is being protected from spambots. You need JavaScript enabled to view it.

Latest discussions

  • No posts to display.