Click here to Skip to main content
15,896,730 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
hi,

Please help me...

I have doubt regarding DB connection. I have called DB in class file and now i want to use this connection in every were in my application. how to call DB connection in Class File to others and use it.

Can you explain with code please?
Posted
Updated 8-Jan-11 1:49am
v2
Comments
thatraja 8-Jan-11 7:49am    
Tags updated

It is not a good idea to leave the connection open through the lifetime of your application. Although, you may have a class which does the opening and closing of the connection for you so that you do not have to write same code again and again. This is something I could suggest:

C#
class DatabaseHelper:IDisposable
    {
        IDbConnection _connection = null;
        public IDbConnection CreateConnection()
        {
            if (_connection == null)
            {
                // create and open the connection here
            }
            else if (_connection.State != ConnectionState.Open)
            {
                _connection.Open();
            }
            return _connection;
        }
        public void Dispose()
        {
            if (_connection != null)
            {
                // Dispose method of some providers do not close the connection even when it is disposed
                _connection.Close();
                _connection.Dispose();
            }
        }
    }


This is just a sample and may fail at various levels depending upon the type of application you have.
 
Share this answer
 
I think what you really want to do is create a static db connection class that that all your code behind classes have access to.
For example: (Please note that I just hammered this code into here without testing it, so there are likely typos and errors, but I think it gives you the idea. It is also incomplete in that you will want to handle disposing it and such at some point.
C#
sealed class DatabaseConnectivity
{
    private static SqlConnection _dbConn = null;

    public static SqlConnection GetConnection()
    {
        if( _dbConn == null )
            _dbConn = new SqlConnection(@"Data Source=.\SQLEXPRESS;AttachDbFilename=D:\Guru\HRP\App_Data\hrp.mdf;Integrated Security=True;User Instance=True"); 

        if( _dbConn.State == ConnectionState.Closed )
            _dbConn.Open();
    }

    return _dbConn;
}


Once you have a class like this, then all you have to do is call it from whichever form uses it.
 
Share this answer
 
Comments
Sandeep Mewara 10-Jan-11 11:40am    
[Off topic]: I replied back here: http://www.codeproject.com/Answers/144431/Application-to-be-started-at-startup.aspx?cmt=40585#answer5.
Espen Harlinn 16-Jan-11 9:21am    
5+ fair answer for a Windows Forms/WPF application
If you are using win forms, see here[^].
 
Share this answer
 
Comments
Guru Brahmam Chowdary 8-Jan-11 6:29am    
Web applications...
Here is a google search that gives you instructions on how to achieve this:
Google[^]

If you are creating a WPF application: Data Binding Overview[^]

Update 1:

Based on your connection string I assume that you are working on an ASP.Net application.

You'll probably want to use the databinding features of asp.net.

SqlConnection con = new SqlConnection(@"Data Source=.\SQLEXPRESS;AttachDbFilename=D:\Guru\HRP\App_Data\hrp.mdf;Integrated Security=True;User Instance=True");


Here is one article here on CP Mastering ASP.NET DataBinding[^] that you may find useful,

This Google search[^], provides you with a ton of reading material.

Example from documentation[^]:
private static void ReadOrderData(string connectionString)
{
    string queryString = 
        "SELECT OrderID, CustomerID FROM dbo.Orders;";
    using (SqlConnection connection = new SqlConnection(
               connectionString))
    {
        SqlCommand command = new SqlCommand(
            queryString, connection);
        connection.Open();
        SqlDataReader reader = command.ExecuteReader();
        try
        {
            while (reader.Read())
            {
                Console.WriteLine(String.Format("{0}, {1}",
                    reader[0], reader[1]));
            }
        }
        finally
        {
            // Always call Close when done reading.
            reader.Close();
        }
    }
}


Usually you don't want to reuse the same connection object instance. Create a new SqlConnection on each request.

Regards
Espen Harlinn
 
Share this answer
 
v3
Comments
Guru Brahmam Chowdary 8-Jan-11 6:49am    
See it is simple application...in that we have

class file
{
//with db connection//

SqlConnection con = new SqlConnection(@"Data Source=.\SQLEXPRESS;AttachDbFilename=D:\Guru\HRP\App_Data\hrp.mdf;Integrated Security=True;User Instance=True");
con.Open();
con.Close();

}

Now this connection should be called where ever we need in this web application. just to avoid every were creating of DB.

So, please explain hoe to call this connection.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900