How do I connect to a SQL Server database using VB?

To connect to a SQL Server database, you can use the SqlConnection class in VB.NET. Here is an example code demonstrating how to connect to a SQL Server database:

Imports System.Data.SqlClient

Public Class Form1
    Dim connString As String = "Data Source=YourServerName;Initial Catalog=YourDatabaseName;User ID=YourUsername;Password=YourPassword"

    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        Using conn As New SqlConnection(connString)
            conn.Open()
            ' 在此处编写您的数据库操作代码
            conn.Close()
        End Using
    End Sub
End Class

In the code above, you need to replace YourServerName, YourDatabaseName, YourUsername, and YourPassword with your own SQL Server server name, database name, username, and password.

In the Button1_Click event handler, we created a SqlConnection object and opened a database connection using the connection string. Once the connection is open, you can write your database operation code here. After completing the operation, use conn.Close() to close the connection.

Please note that this is just a basic example of a connection. In actual programming, you may need to handle some exceptional cases to ensure the safety and reliability of the connection and database operations.

bannerAds