0
  1. Create sqlserver connection in class
  2. call connection class to use all form.

I want to create SQLServer connection in class with C# to use all forms.

Hereabout code of connection in class file

public System.Data.SqlClient.SqlConnection Con = new System.Data.SqlClient.SqlConnection();
public System.Data.SqlClient.SqlCommand Com = new System.Data.SqlClient.SqlCommand();

public string conStr;

public SQL2(string conStr)
{
    try
    {
        Con.ConnectionString = conStr;
        Con.Open();
        Com.Connection = Con;
        Com.CommandTimeout = 3600;
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.Message);
    }
}

public bool IsConnection()
{
    Boolean st;

    if (Con.State==ConnectionState.Open)
    {
        st=true;
    }
    else
    {
        st = false;
    }

    return st;
}  

Can give me full example code?

2
  • Ok, please, try to explain it once again and use English this time. What is your problem? Commented Apr 29, 2012 at 14:08
  • 2
    Close your connections the moment you are done with them. Don't hold them open in a class like this. Commented Apr 29, 2012 at 14:10

1 Answer 1

1

What you probably want is a factory that you use to use to create a connection:

using(var connection = databaseConenctionFactory.Create())
{
    // then do want you want here
}

As LarsTech mentioned you don't want to keep open connections. Open/Use/Close. The using syntax is rather useful here as it takes care of all the unnecessary fluff. So once you are in a habit of using using you will not run into any weird behaviour in production systems.

There is quite a bit around implementing something like this so you could do some research. You could make use of the ADO Provider Factories and use IDbConnection instead of a specific implementation to abstract you implemetation.

You could also usse dependency injection to get to you factory/factories.

So choose your poison :)

Sign up to request clarification or add additional context in comments.

1 Comment

It might be helpful to point out, that by using the 'using-statement', the Dispose() method of the object (in this case connection) is called. This method usually cleans up resources, like closing connections /files. You can (and should) use the using statement on any object that inherits from IDisposable

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.