简体   繁体   中英

C# / SQL Server Connection - bad credentials - Can I set a timeout?

I am trying to make a tool that will allow users to update some table in different databases based on uploaded XML files. I need to let the user select the SQL Server instance, write login credentials, and then, if credentials were right, he will have to chose the database to update.

My problem is that, when username and password provided are wrong, user have to wait like 2-3 second to get the exception that i catch to tell him he typed wrong.

My code looks like this now:

private void comboDatabaseTarget_DropDown(object sender, System.EventArgs e)
        {
            String connString = "Server=" + this.comboSQLServerInstances.Text + ";User Id=sa;Password=testPasswd;";
            try
            {
                using (SqlConnection sqlConn = new SqlConnection(connString))
                {
                    sqlConn.Open();
                    DataTable tblDatabases = sqlConn.GetSchema("Databases");
                    sqlConn.Close();
                    foreach (System.Data.DataRow row in tblDatabases.Select())
                    {
                        this.comboDatabaseTarget.Items.Add(row.ItemArray[0]);
                    }
                }
            }
            catch (Exception ex)
            {

                MessageBox.Show("wrong username and password, or bad sql instance");
            }
        }

My question is: Is there any way to set a timeout when I try to connect to the database? Let's say 100 ms, because if the username and password are right, I will receive the answer almost instantly.

Thank you!

Based on your comment I'd say try setting the SqlConnection.ConnectionTimeout . The default is 15 seconds.

EDIT:

The property is actualy readonly. However, the Remarks section states:

You can set the amount of time a connection waits to time out by using the 
ConnectTimeout or Connection Timeout keywords in the connection string. A value 
of 0 indicates no limit, and should be avoided in a ConnectionString because an 
attempt to connect waits indefinitely.

You can set the connection time out by adding the time to your connection string.

Try adding :-

"Connection Timeout=2;" to the end of of your connection string.

This however is not going to resolve anything. You have created a Try/Catch statement that catches an Exception but your then ignoring the Exception message by creating your own generic message in your MessageBox .

Also, when you use the "Using Statement" like above, you don't need to call for your connection to close, this is done by the using statement automatically.

You can set the login timeout from the connection string itself, see SqlConnectionStringBuilder.ConnectTimeout . The default is 15 seconds. However, setting this timeout much lower (ns) would be a very very very bad idea. The fact that you get an access denied exception it means the login succeeded, and was rejected due to bad credentials. Which means it takes 2-3 seconds to establish the credentials . So setting the login timeout lower would simply close all connections since they simply would time out before they could login! . 2-3 seconds are normal on cold logins (first attempt) because they usually imply cache misses on everything : DNS name, Kerberos tickets, target LSA, SQL authentication token. To keep the application responsive make sure you do not hijack the message pump for 2-3 seconds (ie. test the connection from a background thread).

Some of the previous responses comment make the ususal confussion between login timeout ( SqlConnectionStringBuilder.ConnectTimeout ) and command timeout ( SqlCommand.CommandTimeout ). The two cover different scopes and have, indeed, different defaults (15s vs 30s).

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