65.9K
CodeProject is changing. Read more.
Home

Sql Database Connection DLL Written in C#

starIcon
emptyStarIcon
starIcon
emptyStarIconemptyStarIconemptyStarIcon

1.90/5 (7 votes)

Sep 8, 2005

1 min read

viewsIcon

110704

downloadIcon

2341

Connect and close a sql database with internal error reporting using Event Logs

Introduction

An easy to use DLL written in c# for opening and closing a database.  This DLL has an internal Event Logging in the event that the DLL encounters an error.  The event log will be put into source db error.  Below is a list of Private, public delegates and members.

Public Delegates

SqlConnection Connection - Returns the actual connection to the database.

String Database - Sets or returns the string value for the database name.

String Server - Sets or returns the string value for the server name.

String Sapwd - Sets or returns the string value for the sql authentication password.

Public Members

IsOpen() - Determins the connection state of the connection.  Returns true if open, false if closed.

Open() - Opens the database.  Returns true if it is opened properly.  False if there was an error.  Then logs error in Event Log.

Close() - Closes the database.  Returns true if properly closed. False if error.  Logs error in event log.

setConnection() - Sets the connection string for the SqlConnection to m_conn.
(To use this Member you must either have constructed the Database through first constructor or you must have submitted individual delegates as explained above.)

Private Members

errTrack() - Sets a new Error Log entry and makes the log an error for event viewer.

MessageError() - If there was an error it would show a message box explaining that there was an error and will forward them to event viewer.

 

This is a straight forward approach for database connecting.

To use this you have one of two constructors to use. Please see example execution below.

string dbName = "testdb";

string serverName = "(local)";

string sapwd = "sapwd";
/// Using the standard constructor and inputing all information
/// From the constructor.  This will automatically instantiate the setConnection Member
 
private dbx32sql.Connect conn = new dbx32sql.Connect(dbName, serverName, sapwd);
/// Using the non standard constructor with no inputs. Must initiate setConnection;

private dbx32sql.Connect conn = new dbx32sql.Connect();
conn.Database = dbName;
conn.Server = serverName;
conn.Sapwd = sapwd;
conn.setConnection;

 
try
{
    if (conn.Open)
    {
        string sqlGet = "SELECT COUNT (ID) FROM authors";
        SqlCommand cmdGet = new SqlCommand(sqlGet, conn.Connection);
        int Count = (int)cmdGet.ExecuteScalar();
        CmdGet.Dispose();
    }
    else
    {
        // Input your error handling here;
    }
}
catch(Exception ex)
{
    //insert other error handling.
}
finally
{
    conn.Close();
}