CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 2 of 2
  1. #1
    Join Date
    Nov 2011
    Posts
    4

    Connections SQL Server 2008 R2 (open and close)

    Hi there i hope someone can help me with this issue.

    From another part of the program I want to call a class so I can:

    1. Open a SQL Connection
    2. Do many queries
    3. Close a SQL Connection

    The reason to leave the Connection open is because I want to save workload in the server.

    I have the following code which is not working with CloseCnn().

    Also Im not sure if conn should be a public var so the value doesnt change until I close the Connection.

    Thank you for the help

    Code:
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Data;
    using System.Data.SqlClient;
    using System.Windows.Forms;
    
    namespace PixelCheckSum.Controllers
    {
        class BDController
        {
            public SqlConnection conn;
            public static void OpenCnn()
            {
                // 1. Instantiate the connection
                SqlConnection conn = new SqlConnection("Data Source=(local);Initial Catalog=Northwind;Integrated Security=SSPI");
                try
                {
                    // 2. Open the connection
                    if (conn.State == ConnectionState.Open)
                    {
                        conn.Close();
                    }
                    conn.Open();
                    
                }
                catch(Exception ex)
                {
                    MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
    
            public static void CloseCnn()
            {
                try
                {
                    //Close the connection
                    if (conn != null)
                    {
                        conn.Close();
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
        }
    }

  2. #2
    Join Date
    Dec 2009
    Posts
    109

    Re: Connections SQL Server 2008 R2 (open and close)

    What errors are you getting? And exactly what is it that isn't working?

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured