Solved

Connection to SQL Server 2005

Posted on 2006-11-16
8
267 Views
Last Modified: 2010-04-16
Hi experts,

I have a C# windows form application and I connect to SQL server 2005 using two methods:
1)
SqlCommand cmd = new SqlCommand("select ...", sqlConnectionObject);
2)
SqlDataAdapter mDA = new SqlDataAdapter(("select ...", "Data Source...");
mDA.Fill(someDataTable);

A process is created in SQL server after the first method is called. I have used a single object to limit
the connection. Now, when I called the second method, a new process is created. As a result, there
are two processes for each application in the SQL server!

For SqlDataAdapter, I understand that C# will open a connection if it is not connected,
and closed automatically after use.
C# will remain connect if there is already an opened connection after use.

Question:
How can I limit my application to have only one connection in the SQL server?

regards
0
Comment
Question by:novknow
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 5
  • 3
8 Comments
 
LVL 29

Expert Comment

by:Gautham Janardhan
ID: 17955162
always use one connection object
0
 
LVL 29

Expert Comment

by:Gautham Janardhan
ID: 17955180
u have to write a data acess layer which the whole application will use thru out
0
 
LVL 29

Expert Comment

by:Gautham Janardhan
ID: 17955209
public frmMain()
            {
                  InitializeComponent();
                  AppStartUp.ConnectFromConfigFile();
                  
      
            }


public class AppStartUp
      {
            public static void ConnectFromConfigFile()
            {
                  SQLDBProvider.DataAccess.Connect(" DATA SOURCE="
                        + SC.ConfigurationSettings.AppSettings["SERVER"] + ";"
                        + " PERSIST SECURITY INFO=TRUE;"
                        + " UID=" + SC.ConfigurationSettings.AppSettings["USERNAME"] + ";"
                        + " PWD=" + SC.ConfigurationSettings.AppSettings["PASSWORD"] + ";"
                        + " DATABASE=" + SC.ConfigurationSettings.AppSettings["DATABASE"]);
                                    
                  
                                    
            }
      }
0
Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 

Author Comment

by:novknow
ID: 17955267
Am I doing the correct thing? :

// my class
public sealed class SingleCon
{
    public readonly static string mString = "Data Source.........";

    private static readonly SqlConnection mSQLConn = new SqlConnection(mString);

    public static void Disconnect()
    {
        if (mSQLConn.State != ConnectionState.Closed)
            mSQLConn.Close();
    }

    public static SqlConnection SQLConnection
    {
        get
        {
            try
            {
                if (mSQLConn.State != ConnectionState.Open)
                    mSQLConn.Open();
            }
            catch (SqlException ex)
            {
                // ...
            }

            return mSQLConn;
        }
    }
}

// Connection code #1 :
SqlCommand cmd = new SqlCommand("select...", SingleCon.SQLConnection);

// Connection code #2 :
SqlDataAdapter mDA = new SqlDataAdapter("select...", SingleCon.mString);

Hi gauthampj, appreciate if you could provide example on your second point.

regards
0
 

Author Comment

by:novknow
ID: 17955620
Hi gauthampj,

What is SQLDBProvider?
How do I connect to SQL server with  SqlDataAdapter and SQLDBProvider?

regards
0
 
LVL 29

Accepted Solution

by:
Gautham Janardhan earned 500 total points
ID: 17955789
u r on the rt way
this is another ex


public frmMain()
          {
               InitializeComponent();
               AppStartUp.ConnectFromConfigFile();
               
     
          }


public class AppStartUp
     {
          public static void ConnectFromConfigFile()
          {
               CDataBase.Handle.OpenConnection(" DATA SOURCE="
                    + SC.ConfigurationSettings.AppSettings["SERVER"] + ";"
                    + " PERSIST SECURITY INFO=TRUE;"
                    + " UID=" + SC.ConfigurationSettings.AppSettings["USERNAME"] + ";"
                    + " PWD=" + SC.ConfigurationSettings.AppSettings["PASSWORD"] + ";"
                    + " DATABASE=" + SC.ConfigurationSettings.AppSettings["DATABASE"]);
                             
               
                             
          }
     }
      /// <summary>
      /// Summary description for Class1.
      /// </summary>
      public class CDataBase
      {
                                static CDataBase FObject
            OleDbConnection objCon;
            OleDbCommand objCmd;
            OleDbDataAdapter objAd;
            string strConnectionString;
            string strError;
                                public static CDataBase Handle
                                {
                                         get
                                         {
                                         if(FObject == null)
                                                FObject = new CDataBase();
                                                return FObject ;
                                        }
                                }


            private CDataBase()
            {
                  objCon = new OleDbConnection();
                  objCmd = new OleDbCommand();
                  objAd = new OleDbDataAdapter();
                  strError = "";
                  strConnectionString = "";
            }
            public bool OpenConnection(string ConnectionString)
            {
                  bool flag;
                  try
                  {
                        objCon.ConnectionString = strConnectionString;
                        objCon.Open();
                        objCmd.Connection = objCon;
                        flag = true;
                  }
                  catch(Exception e)
                  {
                        strError = e.ToString();
                        flag = false;
                  }
                  return flag;
            }
            public bool OpenConnection(string ConnectionString)
            {
                  strConnectionString = ConnectionString;
                  return this.OpenConnection();
            }
            public bool CloseConnection()
            {
                  bool flag;
                  try
                  {
                        objCon.Close();
                        flag = true;
                  }
                  catch(Exception e)
                  {
                        strError = e.ToString();
                        flag = false;
                  }
                  return flag;
            }
            public bool ProcessNonSelectQuery(string Query)
            {
                  bool flag;
                  try
                  {
                        objCmd.CommandText = Query;
                        objCmd.ExecuteNonQuery();
                        flag = true;
                  }
                  catch(Exception e)
                  {
                        strError = e.ToString();
                        flag = false;
                  }
                  return flag;
            }
            public DataTable ProcessSelectQuery(string Query)
            {
                  DataSet ds = new DataSet();
                  DataTable dt = null;
                  try
                  {
                        objCmd.CommandText = Query;
                        objAd.SelectCommand = objCmd;      
                        objAd.Fill(ds);
                        dt = ds.Tables[0];
                  }
                  catch(Exception e)
                  {
                        strError = e.ToString();
                        dt = null;
                  }
                  return dt;
            }
            public string Error
            {
                  get
                  {
                        return strError;
                  }
            }
      }
0
 

Author Comment

by:novknow
ID: 17974248
Hi gauthampj,

Thanks for providing the example.
While exploring your example, could you point to me what's wrong with my code (why is it creating an additional process in the SQL server)?

regards
0
 
LVL 29

Expert Comment

by:Gautham Janardhan
ID: 17977946
1)
SqlCommand cmd = new SqlCommand("select ...", sqlConnectionObject);
2)
SqlDataAdapter mDA = new SqlDataAdapter(("select ...", "Data Source...");--- here new connetion will be  made b'coz u r not asking the adaptor to use the connection u have already created....

using my code u could call the adpators overload


SqlDataAdapter mDA = new SqlDataAdapter("Comman',Connection)

or the command s overload


SQLCommand mDA = new SQLCommand ("Comman',Connection)

connection would be CDataBase.Handle.Connection in my case
0

Featured Post

Announcing the Most Valuable Experts of 2016

MVEs are more concerned with the satisfaction of those they help than with the considerable points they can earn. They are the types of people you feel privileged to call colleagues. Join us in honoring this amazing group of Experts.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Article by: Ivo
C# And Nullable Types Since 2.0 C# has Nullable(T) Generic Structure. The idea behind is to allow value type objects to have null values just like reference types have. This concerns scenarios where not all data sources have values (like a databa…
This article describes a simple method to resize a control at runtime.  It includes ready-to-use source code and a complete sample demonstration application.  We'll also talk about C# Extension Methods. Introduction In one of my applications…
Nobody understands Phishing better than an anti-spam company. That’s why we are providing Phishing Awareness Training to our customers. According to a report by Verizon, only 3% of targeted users report malicious emails to management. With compan…
A short tutorial showing how to set up an email signature in Outlook on the Web (previously known as OWA). For free email signatures designs, visit https://www.mail-signatures.com/articles/signature-templates/?sts=6651 If you want to manage em…

738 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question