#region PrepareCommand
private static void PrepareCommand(OleDbCommand command, OleDbConnection connection, OleDbTransaction
transaction, CommandType commandType, string commandText)
{
//if the provided connection is not open, we will open it
if (connection.State != ConnectionState.Open)
{
connection.Open();
}
//associate the connection with the command
command.Connection = connection;
//set the command text (stored procedure name or SQL statement)
command.CommandText = commandText;
//if we were provided a transaction, assign it.
if (transaction != null)
{
command.Transaction = transaction;
}
//set the command type
command.CommandType = commandType;
return;
}
#endregion PrepareCommand
}
In my project I have "Category.mdb" database and in this I have "Tbl_Categories" table which is as below:
catId AutoNumber
catName Text
catDescription Text
addedBy Number
catStatus Text
sysTime Text
Where catId is a primary key.
On Default.aspx page I am having form which accepts the input values.
Here is a code which I can use to add new record by instantiating "OleHelper".
//Page level declarations
OleDbConnection oleCon = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source='D:\\Web\\DbHelper\\App_Data\\Category.mdb'");
OleDbTransaction objTrans = null;
int retInsVal = 0;
protected void btnAdd_Click(object sender, EventArgs e)
{
//Here is how we can create object and pass different parameters to the method
if ((txtCatName.Text.Trim() != "") && (txtDescription.Text.Trim() != ""))
{
//do Db activity
try
{
oleCon.Open();
objTrans = oleCon.BeginTransaction();
string strChkVal = "";
if (chkStatus.Checked == true)
{
strChkVal = "Y";
}
else
{
strChkVal = "N";
}
retInsVal = DbHelper.OleHelper.ExecuteNonQuery(oleCon, objTrans, CommandType.Text, "INSERT INTO
Tbl_Categories (catName,catDescription,addedBy,catStatus,sysTime) VALUES('" + txtCatName.Text.Replace("'", "''").
Trim() + "','" + txtDescription.Text.Replace("'", "''").Trim() + "', 1,'" + strChkVal + "','" +
DateTime.Now.ToLongDateString()+"')");
objTrans.Commit();
lblMessage.Text = "New record added successfully!";
}
catch
{
lblMessage.Text = "An error hsa occured while adding new category!";
objTrans.Rollback();
}
finally
{
//free the resources
oleCon.Close();
}
}
}
I am sure this code will help developer for maintaining two-tier architecture where one can have this class as DataAcccess Layer and aspx files as presentation layer. You can add some more methods to this class like ExecuteScaler() etc. and can extend this article on some project.
Note: In this article I have my project location at "d:\\web\\...\\Category.mdb so in this case my connection becomes as:
OleDbConnection oleCon = new OleDbConnection( "Provider= Microsoft.Jet.OLEDB.4.0;Data Source='D:\\Web\\DbHelper\\App_Data\\Category.mdb'");
In your case it will differ, you can very well store this provider in web.config file or you can use Server.Mappath() to point your database location.