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