简体   繁体   English

C#/ SQL Server连接-凭据错误-我可以设置超时吗?

[英]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. 我正在尝试制作一个工具,该工具将允许用户根据上传的XML文件更新不同数据库中的某些表。 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. 我需要让用户选择SQL Server实例,编写登录凭据,然后,如果凭据正确,则他将不得不选择要更新的数据库。

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. 我的问题是,当提供的用户名和密码错误时,用户必须等待2-3秒才能得到我发现的异常,告诉他他键入了错误。

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. 假设100毫秒,因为如果用户名和密码正确,我几乎会立即收到答案。

Thank you! 谢谢!

Based on your comment I'd say try setting the SqlConnection.ConnectionTimeout . 根据您的评论,我想说尝试设置SqlConnection.ConnectionTimeout The default is 15 seconds. 默认值为15秒。

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 . 您已经创建了一个Try / Catch语句来捕获Exception但是您随后通过在MessageBox创建自己的通用消息来忽略Exception消息。

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. 另外,当您使用上述“使用语句”时,不需要调用关闭连接,这是通过using语句自动完成的。

You can set the login timeout from the connection string itself, see SqlConnectionStringBuilder.ConnectTimeout . 可以从连接字符串本身设置登录超时,请参见SqlConnectionStringBuilder.ConnectTimeout The default is 15 seconds. 默认值为15秒。 However, setting this timeout much lower (ns) would be a very very very bad idea. 但是,将此超时设置得低得多(ns)将是一个非常非常非常糟糕的主意。 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 . 这意味着建立凭据需要2-3秒 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. 冷登录(首次尝试)通常需要2-3秒,因为它们通常暗示缓存未命中所有内容 :DNS名称,Kerberos票证,目标LSA,SQL身份验证令牌。 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). 为了使应用程序保持响应状态,请确保您没有在2-3秒内劫持消息泵(即,从后台线程测试连接)。

Some of the previous responses comment make the ususal confussion between login timeout ( SqlConnectionStringBuilder.ConnectTimeout ) and command timeout ( SqlCommand.CommandTimeout ). 先前的一些响应注释使登录超时( SqlConnectionStringBuilder.ConnectTimeout )和命令超时( SqlCommand.CommandTimeout )之间经常混淆。 The two cover different scopes and have, indeed, different defaults (15s vs 30s). 两者涵盖了不同的范围,并且实际上具有不同的默认值(15秒与30秒)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM