Inserting Data ado.net tutorials

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

This lesson describes how to insert data in a database

When you work with data, you often need to insert data into the data source that is pretty simple and straightforward. You insert specific values for specific columns using the SQL command string.

The Syntax of the Insert Statement is as follows:

    INSERT [INTO] table-name [(column-list)] VALUES (value-list)
  

The following code shows you how to add a single row to a table:

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

      ' declare and create a sql command object
      Dim command As SqlCommand = connection.CreateCommand

      ' set the sql statement to execute at the data source
      command.CommandText = _
      "INSERT INTO Users(Username, Password, FirstName, LastName) " & _
      "VALUES(@Username, @Password, @FirstName, @LastName)"

      ' add the parameters
      command.Parameters.AddWithValue("@Username", Username.Text)
      command.Parameters.AddWithValue("@Password", Password.Text)
      command.Parameters.AddWithValue("@FirstName", FirstName.Text)
      command.Parameters.AddWithValue("@LastName", LastName.Text)

      ' execute the sql statement against the connection
      command.ExecuteNonQuery()

      ' release the resources
      command.Dispose()
    Catch ex As Exception
      Console.Write(ex.Message)
    Finally
      ' close the connection
      connection.Close()
    End Try
  


Share This

Home | About | Contact | Privacy Policy

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