当前位置: 动力学知识库 > 问答 > 编程问答 >

How to connect visual basic 2008 to sql server 2008?

问题描述:

Can anyone please guide me on how to connect Visual Basic 2008 to an SQL server 2008 database? I'm confused on what is the best practice when it comes to this.

网友答案:

There are many many ways. However this is the one of the simplest just using the .net libraries.

  1. you connect to the DB using the server, db and user names and password
  2. you issue a sql command
  3. you collect the results in a sqldatareader
  4. you iterate over the results in the reader
  5. you clean up the the resources.

From: 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

            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
网友答案:

From MSDN : Connecting to Microsoft SQL Server 2008 from Microsoft Visual Studio 2005 and 2008

分享给朋友:
您可能感兴趣的文章:
随机阅读: