Getting data in VB from SQL

I am using Visual Basic 2010 and Microsoft SQL Server 2008. I have my database and my table and I made a connection (at least I think I did) in VB using just an interface.

I want to know how to get data from a database and use it in my VB project. I have certainly looked for solutions already, but the differences I find only confuse me more. I need to know the basics, tools / objects and procedures to retrieve data.

What I am trying to do at the moment is to make a simple selection and put this data into a list immediately after starting the program, for example:

Public Class Form1

    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        SqlConnection1.Open()



        SqlConnection1.Close()

    End Sub
End Class

      

+1


source to share


2 answers


1) Create a connection string

Dim connectionString As String = "Data Source=localhost;........."

      

2) Connect to your database

Dim connection As New SqlConnection(connectionString)
conn.Open()

      

3) Create command and request

Dim command As New SqlCommand("SELECT * FROM Product", connection)
Dim reader As SqlDataReader = command.ExecuteReader()  //Execute the Query

      

4) Get the result. There are several ways



Dim dt As New DataTable()
dt.Load(reader)

'Close the connection
connection.Close()

      

5) Link to your list

myListBox.ItemSource = dt

      

Full code here

Using connection As New SqlConnection(connectionString)
    Dim command As New SqlCommand("Select * from Products", connection)
    command.Connection.Open()
    SqlDataReader reader = command.ExecuteReader()
 End Using

      

For more information

+4


source


SqlConnection1.Open()
using table As DataTable = New DataTable
  using command as SqlCommand = New SqlCommand("SELECT blah blah", SqlConnection1)
    using adapter As SqlDataAdapter = new SqlDataAdapter(command)
      adapter.Fill(table)
    end using
  end using

  for each row As DataRow in table.Rows
    '  add each listbox item
    listbox1.Items.Add(row("column name"))
  next
end using
SqlConnection1.Close()

      



0


source







All Articles