Connect SQL Server on button click VB.net

本秂侑毒 提交于 2020-01-03 03:45:10

问题


How to connect SQL Server on button click?
I want to manually enter the Server, Username and Password into textboxes.

I have a code here but I'm not sure if it's correct.

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

Idk how to check if the connection is correct or not. If the input is right or wrong.
Please give me full code example. Thank you!


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


来源:https://stackoverflow.com/questions/33090524/connect-sql-server-on-button-click-vb-net

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