Creating ADO.NET Commands ado.net tutorials

Tags: VB.NET, VB 2008, VB 2010, VB 2012, VB 2013

This lesson describe how to create command

After creating a connection to the database, you need to start interacting with data in order to retrieve, add, update, or delete some data, or modify the database in some other way. For that purpose you should involve a command.

Each command must be associated with a connection to the database, by setting the connection property of the command before the command can be executed.

    Dim ConnectionString As String = _
    "Data Source=SqlServerNameOrIP;Initial Catalog=DBName;Integrated Security=True"
    Dim connection As New SqlConnection(ConnectionString)
    Try
      connection.Open()

      ' Way #1
      Dim command As New SqlCommand
      command.Connection = connection
      command.CommandText = "SELECT * FROM aspnet_Users"

      ' Way #2
      Dim command As SqlCommand = connection.CreateCommand
      command.CommandText = "SELECT * FROM aspnet_Users"

      ' Way #3 (put everything together)
      Dim command As New SqlCommand("SELECT * FROM aspnet_Users", connection)
      '...
  

In order to save resources, the same connection can be used by multiple commands.

    Dim ConnectionString As String = _
    "Data Source=SqlServerNameOrIP;Initial Catalog=DBName;Integrated Security=True"
    Dim connection As New SqlConnection(ConnectionString)
    Try
      connection.Open()
      ' Command #1
      Dim commandOne As SqlCommand = connection.CreateCommand
      commandOne.CommandText = "SELECT * FROM aspnet_Users"
      ' Todo: read from the table users

      ' Command #2
      Dim commandTwo As SqlCommand = connection.CreateCommand
      commandTwo.CommandText = "SELECT * FROM aspnet_Roles"
      ' Todo: read from the table roles
      '...
  


Share This

Home | About | Contact | Privacy Policy

Copyright visual-basic-tutorials.com 2017 - All Rights Reserved.