如何将visual basic 2008连接到sql server 2008?

时间:2012-01-02 11:09:22

标签: sql-server-2008 visual-studio-2008

有人可以指导我如何将Visual Basic 2008连接到SQL Server 2008数据库吗?我对这方面的最佳做法感到困惑。

2 个答案:

答案 0 :(得分:1)

有很多方法。然而,这是最简单的使用.net库之一。

  1. 使用服务器,数据库和用户名和密码连接到数据库
  2. 发出sql命令
  3. 您在sqldatareader中收集结果
  4. 您在阅读器中迭代结果
  5. 你清理资源。
  6. 来自: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)