Products
Services
Contact Us

Scripts: asp :: MS SQL and Database :: Library Article #10

Developer's Section

Insert Data to a MS SQL Server Database using ASP.NET
By: Erobo Team Member

Hire a Developer for Related Work / Installation | $55 hr
Rating:  | Rate It:   
Average Votes: (1841)
Favorites:

Learn to use the System.Data.SqlClient to connect to a MS SQL Database and insert data into it.

In this tutorial we will learn how to insert data to a table using ASP.NET and a Microsoft SQL Server Database. For this code to work, you are going to need the System.Data.SqlClient namespace. The following scripts creates a new connection, inserts some data to a table, and retrieves the ID of the newly inserted item.

 Code Snippet 1

<%@ Page Language="VB" Debug="true" %>
<%@ Import Namespace="System.Data" %>
<%@ Import Namespace="System.Web.Security" %>
<%@ Import Namespace="System.Data.SqlClient" %>
<%@ Import Namespace="System.IO" %>
<%@ Import Namespace="System.Math" %>

<script language="vb" runat="server">


Dim conn = "server=111.111.11.284;" 'specify server address here
conn = conn & "database=db_pbifilmfest_org;" 'specify database name here
conn = conn & "uid=dbm.pbifilmfest.org;" 'specify user id here
conn = conn & "password=bitsy"      'specify password here            

'create a connection object
Dim CONNECTOR As New System.Data.SqlClient.SqlConnection(conn)
   
 Sub Page_Load(ByVal Source As Object, ByVal E As EventArgs)
  
     Q = Q &"insert employee (empID,"
     Q = Q &" emp_firstname, emp_lastname, emp_phone) values ("
     Q = Q & "@empID, @emp_firstname, @emp_lastname, @emp_phone);"
     Q = Q & " select @@identity"

    Dim myCommand As New SqlCommand(Q, CONNECTOR)
    myCommand.Parameters.Add(New SqlParameter("@empID", "12345"))
    myCommand.Parameters.Add(New SqlParameter("@emp_firstname", "Joe"))
    myCommand.Parameters.Add(New SqlParameter("@emp_lastname", "Sanders"))
    myCommand.Parameters.Add(New SqlParameter("@emp_phone", "954-456-4535"))

    CONNECTOR.Open()

    'insert data and retrieve id
    Dim newID = myCommand.ExecuteScalar

    CONNECTOR.Close()

 End Sub

</script>




See other Scripts in MS SQL and Database

Submit Your Scripts:

If you would like to have your ASP & ASP.NET scripts published in this section please fill out
the form below:
*Your Name or Username:
Home Town:
*Email:
*Description and Code:
*Enter Code shown
to the right:

[ Refresh Image ]