有人可以指导我如何将Visual Basic 2008连接到SQL Server 2008数据库吗?我对这方面的最佳做法感到困惑。
答案 0 :(得分:1)
有很多方法。然而,这是最简单的使用.net库之一。
来自:How to ADO.NET SqlDataReader
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 connectionString As String
Dim sqlCnn As SqlConnection
Dim sqlCmd As SqlCommand
Dim sql As String
' Use this first connection string if using windows auth
' connectionString = "Data Source=ServerName;Initial Catalog=DatabaseName;Integrated Security=True"
connectionString = "Data Source=ServerName;Initial Catalog=DatabaseName;User ID=UserName;Password=Password"
sql = "Your SQL Statement Here , like Select * from product"
sqlCnn = New SqlConnection(connectionString)
Try
sqlCnn.Open()
sqlCmd = New SqlCommand(sql, sqlCnn)
Dim sqlReader As SqlDataReader = sqlCmd.ExecuteReader()
While sqlReader.Read()
MsgBox(sqlReader.Item(0) & " - " & sqlReader.Item(1) & " - " & sqlReader.Item(2))
End While
sqlReader.Close()
sqlCmd.Dispose()
sqlCnn.Close()
Catch ex As Exception
MsgBox("Can not open connection ! ")
End Try
End Sub
End Class
答案 1 :(得分:0)