Products
Services
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: (2951)
Favorites:

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=111.11.11.1;" '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"))

    CONNECTOR.Open()

    myCommand.ExecuteScalar()
    
    '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")

    CONNECTOR.Close()

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


End Sub

</script>


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:
*Email:
*Description and Code:
*Enter Code shown
to the right:

[ Refresh Image ]