Contact Us

Scripts: asp :: MySQL and Database :: Library Article #11

Developer's Section

Insert Data to a Mysql Database using ASP.NET and ODBC Driver
By: Erobo Team Member

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

Learn a simple technique to insert data to a MySql database using the System.Data.Odbc namespace for ASP.NET.

Use the Namespace System.Data.Odbc to connect to a mysql database using ASP.NET. The script will create a connection to the database, insert data into table employee, and retrieve the id of the last record inserted.

 Code Snippet 1

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

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

Dim conn as String = "DRIVER={MySQL ODBC 3.51 Driver};"
    conn = conn & "SERVER=;" 'specify server address
    conn = conn & "DATABASE=myDbName;"  'specify database name
    conn = conn & "USER=mydbUser;"      'specify db user
    conn = conn & "PASSWORD=myDbPassword;" 'specify db password
    conn = conn & "Option=3;"             'option 3 on

'create a connection object
Dim CONNECTOR As OdbcConnection = New OdbcConnection(conn)
Sub Page_Load(ByVal Source As Object, ByVal E As EventArgs)

    Q = "insert into employee (empID, emp_firstname, "
    Q = Q & "emp_lastname, emp_phone) values"
    Q = Q & "(?, ?, ?, ?)"

    Dim myCommand As New OdbcCommand(Q, CONNECTOR)
    myCommand.Parameters.Add(New OdbcParameter("@empID", "12456"))
    myCommand.Parameters.Add(New OdbcParameter("@emp_firstaname", "Joe"))
    myCommand.Parameters.Add(New OdbcParameter("@emp_lastname", "Sanders"))
    myCommand.Parameters.Add(New OdbcParameter("@emp_phone", "933-345-3464"))


    'query again to get id of new employee
    Q = "select LAST_INSERT_ID() from employee"

    Dim myResult As DataSet = New DataSet()
    Dim da As OdbcDataAdapter = New OdbcDataAdapter(Q, CONNECTOR)

    da.Fill(myResult, "empID")


    'get id of newly inserted employee
    Dim newID As String = myResult.Tables("empID").Rows(0).Item(0)

End Sub


See other Scripts in MySQL 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:
*Description and Code:
*Enter Code shown
to the right:

[ Refresh Image ]