In this page I would like to teach you on how to create a successful and useful data base connection to your Visual Studio Program. So as a beginning to our journey on codding this is the most perfect step to begin with.
This is called "Connection Manager" in your Program and you can do this coding in a new C# class.(You can name it in any way you like.)
You have to create a new project and name the project with .DATA at the end. (".DATA" is not an extension name, we just name so for our ease of reference.)
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.SqlClient;
namespace HRMS.DATA
{
public class ConnectionManager
{
private SqlConnection oSQLCon;
private SqlCommand oSQLCom;
private SqlTransaction oSQLTrans;
/// <summary>
/// THE FOLLOWING IS A CONSTRUCTER.
/// </summary>
public ConnectionManager()
{
oSQLCon = new SqlConnection();
oSQLCon.ConnectionString = this.BuildConnectionString();
}
/// <summary>
/// THE FOLLOWING IS A METHOD.
/// </summary>
/// <returns></returns>
public string BuildConnectionString()
{
SqlConnectionStringBuilder oConStrBuild = new SqlConnectionStringBuilder();
oConStrBuild.DataSource = "SQL SERVER"; // This is the name of the SQL Server.
oConStrBuild.InitialCatalog = "HRxxxx"; // This is the name of your SQL Database
oConStrBuild.UserID = "sa"; // This is your SQL Server User name.
oConStrBuild.Password = "#comxxxx"; // This is your SQL Server Password.
return oConStrBuild.ConnectionString;
}
public void BeginTransaction()
{
try
{
if (oSQLCon.State != System.Data.ConnectionState.Open)
{
oSQLCon.Open();
oSQLTrans = oSQLCon.BeginTransaction();
}
}
catch
{
throw;
}
}
public void CommitTransaction()
{
try
{
oSQLTrans.Commit();
}
catch
{
throw;
}
}
public void RollbackTransaction()
{
try
{
oSQLTrans.Rollback();
}
catch
{
throw;
}
}
public SqlCommand CreateCommand(string CommandText)
{
try
{
oSQLCom = new SqlCommand();
oSQLCom.CommandText = CommandText;
oSQLCom.Connection = this.oSQLCon;
oSQLCom.Transaction = this.oSQLTrans;
return oSQLCom;
}
catch
{
throw;
}
}
}
}
After that create another class call "DataAccessManager". And to the following coding.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.SqlClient;
namespace HRMS.DATA
{
public class DataAccessManager
{
protected SqlDataAdapter oDa;
protected SqlDataReader oDr;
protected int ReturnValue;
protected ConnectionManager oConMan;
public DataAccessManager()
{
oConMan = new ConnectionManager();
}
}
}
After you have done the above coding sucessfuly, you do not need to create data base connections again and again on you program thus you can initiate a connection by using the above code
Lesson 09--> Home
No comments:
Post a Comment