How to use Try Catch to display Login failure for (App.Config) connection string

可紊 提交于 2019-12-25 03:34:53

问题


My coding is simplified by using a single line of code to connect to MS-SQL 2008 R2 Databases. However I wish to have a msgbox displayed on login/password failure. Here's the coding.

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

<< catch error required >>

Thanks.


回答1:


First assign the value to app.config connection string:

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

Then use Try Catch Block. If connection fails use yor message box in catch block.

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

Declare globalConnStr as global variable and when you are done with the checking of the login credentials assign the connection string to globalConnStr. After this you can use the globalConnStr string as many times you want in your program.



来源:https://stackoverflow.com/questions/8815022/how-to-use-try-catch-to-display-login-failure-for-app-config-connection-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!