How to use Try Catch to display Login failure for

2019-08-25 05:39发布

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条回答
冷血范
2楼-- · 2019-08-25 05:54

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.

查看更多
登录 后发表回答