Introduction
Data management and retrieval in modern web development depend heavily on the smooth integration of databases. This article explores building a powerful Data Access Layer (DAL) in C# that is intended to communicate with a MySQL database. An example of how to implement such a DAL is given in the provided code.
The ClsDal class is responsible for interacting with a MySQL database. It contains methods to retrieve data from the database and handle connection strings.
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;
using MySql.Data.MySqlClient;
namespace DemoAPI.DB_Logic
{
public class ClsDal
{
private static string mstrPath = null;
static ClsCommonCryptography mobjCryptography = new ClsCommonCryptography();
public static DataSet Qry_WithDataSet(string ProcWithParameter)
{
IErrorRepository error = new ErrorRepository();
DataSet ds = new DataSet();
try
{
if (GetConnStr() != null)
{
MySqlConnection sqlCon = new MySqlConnection(mstrPath);
sqlCon.Open();
MySqlCommand sqlCmd = new MySqlCommand(ProcWithParameter, sqlCon);
sqlCmd.CommandTimeout = 0;
MySqlDataAdapter sqlDataAdapter = new MySqlDataAdapter
{
SelectCommand = sqlCmd
};
DataSet dtReturn = new DataSet();
sqlDataAdapter.Fill(dtReturn);
sqlCmd.Dispose();
sqlDataAdapter.Dispose();
sqlCon.Dispose();
return dtReturn;
}
else
{
return null;
}
}
catch (MySqlException sqlEx)
{
error.DBlogError("Qry_WithDataSet", ProcWithParameter, "Output" + "\n" + sqlEx.ToString());
return null;
}
catch (Exception ex)
{
error.DBlogError("DBError Method : Qry_WithDataSet", ProcWithParameter, "Output" + "\n" + ex.ToString());
return null;
}
}
private static string GetConnStr()
{
IErrorRepository error = new ErrorRepository();
try
{
mstrPath = System.Configuration.ConfigurationManager.ConnectionStrings["DbConn"].ConnectionString.ToString();
mstrPath = mobjCryptography.StringDecrypt(mstrPath);
return mstrPath;
}
catch (Exception ex)
{
error.DBlogError("DBError Method : GetConnStr", mstrPath, "Output" + "\n" + ex.ToString());
return null;
}
}
}
}
Join the conversation! Your thoughts help the community grow.