2012-01-11 26 views
0

通過使用一行代碼連接到MS-SQL 2008 R2數據庫,可以簡化我的編碼。不過,我希望在登錄/密碼失敗時顯示msgbox。這是編碼。如何使用Try Catch顯示(App.Config)連接字符串的登錄失敗

My.Settings.Item("CustomerConnectionString") = "Data Source=.\SQLEXPRESS; Initial   
Catalog=customer; uid = temp ; pwd = temp" 

<< catch error required >> 

謝謝。

+0

你的問題到底是什麼?順便說一句,你可能最好簡化這段代碼,以防止簡單的SQL注入攻擊。 – Afshin 2012-01-11 06:26:37

回答

0

首先分配值的app.config連接字符串:

My.Settings.Item("CustomerConnectionString") = "Data Source=FAROOK-PC\SQLEXPRESS;Initial 
Catalog= '" & Me.ComboBox1.Text & "'; uid = '" & Me.Login1.Text & "'; pwd = '" & 
Me.Password1.Text & "'" 

然後使用try catch塊。如果連接失敗,則使用catch塊中的yor消息框。

Dim sqlCnn As New SqlConnection 
Dim connString as string = My.Settings.Item("CustomerConnectionString").value 

Try 
    sqlCnn = New SqlConnection(connString) 
    sqlCnn.open() 
    globalConnStr = connString 
Catch ex As SqlException 
    MsgBox("Login Failed") 
Finally 
    sqlCnn.close() 
End Try 

聲明globalConnStr爲全局變量,當你與登錄憑證的檢查進行分配連接字符串globalConnStr。之後,您可以在程序中多次使用globalConnStr字符串。

+0

極客,上面的代碼應該可以工作。一旦我粘貼了編碼和測試,我會回來。 – Farook 2012-01-12 06:10:15

+0

極客代碼工作正常。無法從My.Settings.Conn獲取.Value,所以我使用了ToString。我將以回答的方式解答這篇文章。謝了哥們! – Farook 2012-01-12 06:24:03

+0

歡迎光臨。如果解決方案有幫助,也可以將以前的問題標記爲回答。 http://stackoverflow.com/questions/8817040/how-to-display-a-login-failure-messagebox-for-app-config-connection-string – Harsh 2012-01-12 06:26:24