简体   繁体   中英

SqlConnection by Method

I'm trying to implement a method that will provide the SqlConnection , how should I do it?

public class DAL
{
    public bool dbCon()
    {
        string comboValue;

        try
        {
            using (SqlConnection sqlConn =
                new SqlConnection(@"Data Source =VirtualXP-64805;Initial Catalog=CTS_Demo;Integrated Security=SSPI"))
            {
                sqlConn.Open();
            }
        }
        catch (SqlException Ex)
        {
            MessageBox.Show(Ex.ToString());
        }
    }
}

You method should return the connection object not a bool value, or you may define a class level connection variable and use that.

But When it comes to Database Connection then open it as late as possible and close it as early as possible

Instead of opening the connection from the method you may simply return the connection object and open it where you need it. Something like:

public SqlConnection dbCon()
{
 return new SqlConnection(@"Data Source =VirtualXP-64805;Initial Catalog=CTS_Demo;Integrated Security=SSPI");
}

and then where you are using it:

using(SqlConnection conn = dbCon())
{
  conn.Open();
  .... your code
}

Or you can get rid of the method and simply call the new SqlConnection with connection string from the configuration.

EDIT:

Since you want to return an open connection from your method, you can do the following, but IMO its not the recommended way, you have to call Dispose manually for each connection object, since you will not use it within using statement.

public SqlConnection dbCon()
{
 SqlConnection sqlConn;

 try
 {
   sqlConn = new SqlConnection(@"Data Source =VirtualXP-64805;Initial Catalog=CTS_Demo;Integrated Security=SSPI")

 }
 catch(SqlException)
 {
  //your exception handling details
  sqlConn = null;
 }
return sqlConn;

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM