Tuesday, October 10, 2006

connecting a database with c# / asp.net

this is the code of database connection and sql executing functions

using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data.OleDb;

///


/// data base class
///

public class db
{
OleDbConnection gDbConn;
OleDbCommand gDbCmd;
public string error;
public db(string connStr)
{
try
{
gDbCmd = new OleDbCommand();
gDbConn = new OleDbConnection();
gDbConn.ConnectionString = connStr;
error="class built successfully";
}
catch (Exception e)
{
error = "[class constructor] building class faild, error in connecting database error discribe: "+e.Message ;
}
}
public OleDbDataReader executeSQL(String sql)
{
try
{
OleDbDataReader rs ;
gDbConn.Open();
gDbCmd.Connection = gDbConn;
gDbCmd.CommandText = sql;
if (sql.Contains("select") )
rs = gDbCmd.ExecuteReader();
else
{
gDbCmd.ExecuteNonQuery();
rs = null;
}
error = "executeSQL executed successfully";
return rs;
}
catch(Exception e)
{
error = "[execute sql] failed to execute sql statement error discribe:" + e.Message
return null;
}
}
}

an example of using this class here: http://byramix.blogspot.com/2006/10/using-data-base-class.html



No comments: