SQL Connection Failure/Error RRS feed

  • Question


    Hi guys... i'm quite new here... and as a C# programming too....


    public void EstablishCn()




    cnConnection = new SqlConnection();

    cnConnection.ConnectionString = strConnection;



    catch (Exception ex)


    MessageBox.Show("Failed Connection on: "+ ex.Message, "Error");





    if (cnConnection.State == System.Data.ConnectionState.Closed)








    I can't seem to get a successfull connection to the database... i keep finding out why. I've done the same strategy on other programs but this one with slight variations just won't work... thanks in advance! Big Smile


    Here's my connection String:


    public class Common


    public static SqlConnection cnConnection;

    public static string strConnection = "Data Source = local; Initial Catalog = CHARLES_DB";

    public static string strQuery;




    Saturday, November 17, 2007 2:32 AM


All replies

  • I might be missing something outside your pasted code but in order to use the static members of Common you should use:


    Common.cnConnection = new SqlConnection();

    Common.cnConnection.ConnectionString = Common.strConnection;



    If I'm missing something then maybe it's your connection string, but I suck at those, I keep mine in a little text file and copy paste them when I need them :/

    Saturday, November 17, 2007 2:40 AM
  • I don't know which version of SQL Server you are using but I would check the following for valid connection string examples:





    Monday, November 19, 2007 4:15 PM
  • I suggest that you 'cheat' a little bit like the previous reply.  He uses a text file to save strings, so do I.  I get them by using the Visual Studio C# connection wizard.  Take a look at the opening screen of the wizard, the one where you designate your connection.  Look down toward the bottom and you should see the word ConnectionString with a " + " sign inside of a box adjacent to it. 


    Click the " + " sign and it will display the connection string for the connection that you defined in the top half of the page.  Copy and paste the string somewhere safe, and you should be good.  Click "Cancel", and you're done.



    "Stuck in a procedural world since 1971."

    Monday, November 19, 2007 5:54 PM
  • Hi,

    Also note that openning a connection and setting it in a static object is not good.  The best practice is to open the connection when database work must be done and to close it as soon as possible.  Connection pooling will do the rest.

    Sunday, December 2, 2007 7:35 PM