SQL Server Connection Timeout C#

Posted by Termin8tor on Stack Overflow See other posts from Stack Overflow or by Termin8tor
Published on 2012-12-10T10:54:07Z Indexed on 2012/12/10 11:05 UTC
Read the original article Hit count: 155

First off I'd like to let everyone know I have searched my particular problem and can't seem to find what's causing my problem.

I have an SQL Server 2008 instance running on a network machine and a client I have written connecting to it.

To connect I have a small segment of code that establishes a connection to an sql server 2008 instance and returns a DataTable populated with the results of whatever query I run against the server, all pretty standard stuff really. Anyway the issue is, whenever I open my program and call this method, upon the first call to my method, regardless as to what I've set my Connection Timeout value as in the connection string, it takes about 15 seconds and then times out. Bizarrely though the second or third call I make to the method will work without a problem.

I have opened up the ports for SQL Server on the server machine as outlined in this article: How to Open firewall ports for SQL Server and verified that it is correctly configured. Can anyone see a particular problem in my code?

    string _connectionString = "Server=" + @Properties.Settings.Default.sqlServer + "; Initial Catalog=" + @Properties.Settings.Default.sqlInitialCatalog +
        ";User Id=" + @Properties.Settings.Default.sqlUsername + ";Password=" + @Properties.Settings.Default.sqlPassword + "; Connection Timeout=1";

    private DataTable ExecuteSqlStatement(string command)
    {
        using (SqlConnection conn = new SqlConnection(_connectionString))
        {
            try
            {
                conn.Open();
                using (SqlDataAdapter adaptor = new SqlDataAdapter(command, conn))
                {
                    DataTable table = new DataTable();
                    adaptor.Fill(table);
                    return table;
                }
            }
            catch (SqlException e)
            {
                throw e;
            }
        }
    }

The SqlException that is caught at my catch is : "Timeout expired. The timeout period elapsed prior to completion of the operation or the server is not responding."

This occurs at the conn.Open(); line in the code snippet I have included. If anyone has any ideas that'd be great!

© Stack Overflow or respective owner

Related posts about c#

Related posts about .NET