[英]C# / SQL Server Connection - bad credentials - Can I set a timeout?
我正在嘗試制作一個工具,該工具將允許用戶根據上傳的XML文件更新不同數據庫中的某些表。 我需要讓用戶選擇SQL Server實例,編寫登錄憑據,然后,如果憑據正確,則他將不得不選擇要更新的數據庫。
我的問題是,當提供的用戶名和密碼錯誤時,用戶必須等待2-3秒才能得到我發現的異常,告訴他他鍵入了錯誤。
我的代碼現在看起來像這樣:
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");
}
}
我的問題是:嘗試連接數據庫時,是否可以設置超時? 假設100毫秒,因為如果用戶名和密碼正確,我幾乎會立即收到答案。
謝謝!
根據您的評論,我想說嘗試設置SqlConnection.ConnectionTimeout 。 默認值為15秒。
編輯:
該屬性實際上是只讀的。 但是,“備注”部分指出:
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.
您可以通過將時間添加到連接字符串中來設置連接超時。
嘗試添加:-
"Connection Timeout=2;"
到連接字符串的末尾。
但是,這不會解決任何問題。 您已經創建了一個Try / Catch語句來捕獲Exception
但是您隨后通過在MessageBox
創建自己的通用消息來忽略Exception消息。
另外,當您使用上述“使用語句”時,不需要調用關閉連接,這是通過using語句自動完成的。
您可以從連接字符串本身設置登錄超時,請參見SqlConnectionStringBuilder.ConnectTimeout 。 默認值為15秒。 但是,將此超時設置得低得多(ns)將是一個非常非常非常糟糕的主意。 您收到拒絕訪問異常的事實意味着登錄成功,並且由於憑據不正確而被拒絕。 這意味着建立憑據需要2-3秒 。 因此,將登錄超時設置得較低可以簡單地關閉所有連接,因為它們只會在登錄之前超時! 。 冷登錄(首次嘗試)通常需要2-3秒,因為它們通常暗示緩存未命中所有內容 :DNS名稱,Kerberos票證,目標LSA,SQL身份驗證令牌。 為了使應用程序保持響應狀態,請確保您沒有在2-3秒內劫持消息泵(即,從后台線程測試連接)。
先前的一些響應注釋使登錄超時( SqlConnectionStringBuilder.ConnectTimeout
)和命令超時( SqlCommand.CommandTimeout
)之間經常混淆。 兩者涵蓋了不同的范圍,並且實際上具有不同的默認值(15秒與30秒)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.