如何使用 Try Catch 显示 (App.Config) 连接字符串的登录失败 [英] How to use Try Catch to display Login failure for (App.Config) connection string

查看:26
本文介绍了如何使用 Try Catch 显示 (App.Config) 连接字符串的登录失败的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

通过使用一行代码连接到 MS-SQL 2008 R2 数据库,我的编码得到了简化.但是我希望在登录/密码失败时显示一个 msgbox.这是编码.

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 >>

谢谢.

推荐答案

先给 app.config 连接字符串赋值:

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 & "'"

然后使用 Try Catch Block.如果连接失败,请在 catch 块中使用您的消息框.

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

将 globalConnStr 声明为全局变量,当您完成登录凭据的检查后,将连接字符串分配给 globalConnStr.在此之后,您可以在程序中多次使用 globalConnStr 字符串.

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.

这篇关于如何使用 Try Catch 显示 (App.Config) 连接字符串的登录失败的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆