【问题标题】:Connect SQL Server on button click VB.net在按钮单击 VB.net 上连接 SQL Server
【发布时间】:2016-01-10 11:41:20
【问题描述】:

如何在单击按钮时连接 SQL Server?
我想在文本框中手动输入服务器、用户名和密码。

我这里有一个代码,但我不确定它是否正确。

Private Sub SQLConnect_Click(sender As Object, e As EventArgs) Handles SQLConnect.Click
    Dim con As SqlConnection = New SqlConnection("Server=" & SQLServer.Text & ";Database=GameDB;User Id=" & SQLUser.Text & ";Password=" & SQLPwd.Text & ";")
    con.Open()
        MsgBox("Successfully Connected!")
    'con.Close()
End Sub

想知道如何检查连接是否正确。如果输入正确或错误。
请给我完整的代码示例。谢谢!

【问题讨论】:

  • 参数名称应该是Password,而不是Pwd
  • 你为什么要把服务器密码给用户……永远?
  • @Plutonix 你在说什么?我将要求用户提供服务器密码以使用我的应用程序。

标签: sql-server vb.net connection-string


【解决方案1】:
Imports System.Data.SqlClient
Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
    Dim connetionString As String
    Dim cnn As SqlConnection
    connetionString = "Data Source=ServerName;Initial Catalog=DatabaseName;User ID=UserName;Password=Password"
    cnn = New SqlConnection(connetionString)
    Try
        cnn.Open()
        MsgBox("Connection Open ! ")
        cnn.Close()
    Catch ex As Exception
        MsgBox("Can not open connection ! ")
    End Try
End Sub
End Class

【讨论】:

    【解决方案2】:
    Dim builder As New SqlConnectionStringBuilder()
    builder.DataSource = SQLServer.Text
    builder.InitialCatalog = "GameDB"
    builder.UserID = SQLUser.Text
    builder.Password = SQLPwd.Text
    builder.ApplicationName = "MyGame"
    
    Using connection As New SqlConnection(builder.ConnectionString)
       Try
           connection.Open()
           MsgBox("Connection can be opened")
       Catch ex As Exception
           MsgBox("Connection can not be opened: " & vbCrLf & ex)
       End Try
    End Using
    

    【讨论】:

    • 我尝试使用此代码,但它显示“'builder' is not declared”
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-09-17
    • 1970-01-01
    • 2011-10-28
    • 1970-01-01
    • 1970-01-01
    • 2011-11-22
    • 1970-01-01
    相关资源
    最近更新 更多