I'm currently working with an application connected to a local SQL Server database on my machine. I have a number of SQL queries currently executing fine using different methods. My question is regarding the Opening/closing of the database connection between the different methods.
I have 2 methods looking something like this:
Class MyClass
{
string connectionString = "myConnectionString";
public void Method1()
{
SqlConnection con = new SqlConnection(connectionString);
con.Open();
string sqlStr = "my SQL query";
SqlCommand com = new SqlCommand(sqlStr, con);
com.ExecuteNonQuery();
con.Close();
}
public void Method2()
{
SqlConnection con = new SqlConnection(connectionString);
con.Open();
string sqlStr = "my SQL query";
SqlCommand com = new SqlCommand(sqlStr, con);
com.ExecuteNonQuery();
con.Close();
}
}
If I call these methods they work fine, no exceptions. But is this the proper way of handling database connections? Could I for example use a static connection that is initialized as soon as MyClass gets initialized? Like this
Class MyClass
{
string connectionString = "myConnectionString";
SqlConnection con = new SqlConnection(connectionString);
con.Open();
public void Method1()
{
...
}
etc.
or is there a "better" way to handle database connections?
I'm thankful for any input.