Inserting a new record into sql db using user-entered information

Last post 11-23-2006 4:19 PM by diehardguy. 4 replies.

Sort Posts:

  • Tongue Tied [:S] Inserting a new record into sql db using user-entered information

    11-22-2006, 3:10 PM
    • Loading...
    • rox163
    • Joined on 11-22-2006, 8:04 PM
    • Posts 6

    Im trying to add a new rcord to my db on a button click usign the following code

     

    'data adapter

    Dim dAdapt1 As New SqlClient.SqlDataAdapter

    'create a command object

    Dim objCommand As New SqlClient.SqlCommand

    'command builder

    Dim builderT As SqlClient.SqlCommandBuilder

    'connection string

    Dim cnStr As String = "Data Source=ELEARN-FRM-BETA;Initial Catalog=StudentPlayGround;Integrated Security=True"

    'dataset

    Dim dsT As DataSet

    Private Sub connect()

    'connection

    objCommand.Connection =

    New SqlClient.SqlConnection(cnStr)

    'associating the builder with the data adapter

    builderT =

    New SqlClient.SqlCommandBuilder(dAdapt1)

    'opening the connection

    objCommand.Connection.Open()

    'query string

    Dim query As String = "SELECT * from StudentPlayground..Employees"

    'setting the select command

    dAdapt1.SelectCommand =

    New SqlClient.SqlCommand(query, objCommand.Connection)

    'dataset

    dsT =

    New DataSet("Trainee Listings")

    dAdapt1.Fill(dsT,

    "Employees")

    End Sub

    Private Sub BindData()

    connect()

    DataBind()

    End Sub

    Protected Sub submitButton_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles submitButton.Click

    Dim empID As Integer = CType(FindControl("TextBox8"), TextBox).Text

    BindData()

    Dim firstName As String = CType(FindControl("TextBox1"), TextBox).Text

    BindData()

    Dim lastName As String = CType(FindControl("TextBox2"), TextBox).Text

    BindData()

    Dim location As String = CType(FindControl("TextBox3"), TextBox).Text

    BindData()

    Dim termDate As Date = CType(FindControl("TextBox4"), TextBox).Text

    BindData()

    Dim hireDate As Date = CType(FindControl("TextBox7"), TextBox).Text

    BindData()

    Dim dept As String = CType(FindControl("TextBox5"), TextBox).Text

    BindData()

    Dim super As String = CType(FindControl("TextBox6"), TextBox).Text

    BindData()

    Dim newRow As DataRow = dsT.Tables("Employees").NewRow

    newRow.BeginEdit()

    newRow.Item(0) = empID

    newRow.Item(1) = firstName

    newRow.Item(2) = lastName

    newRow.Item(3) = location

    newRow.Item(4) = hireDate

    newRow.Item(5) = termDate

    newRow.Item(6) = dept

    newRow.Item(7) = super

    newRow.EndEdit()

     

    'do the update

    Dim insertStr As String = "INSERT INTO Employees" + _

    "(EmployeeID,FirstName,LatName,Location,HireDate,TerminationDate,Supervisor)" + _

    "VALUES (empID,firstName,lastName,location,hireDate,termDate,dept,super)"

    Dim insertCmd As SqlClient.SqlCommand = New SqlClient.SqlCommand(insertStr, objCommand.Connection)

    dAdapt1.InsertCommand() = insertCmd

     

    dAdapt1.Update(dsT,

    "Employees")

    'Dim insertCmd As new SqlClient.SqlCommand = (builderT.GetInsertCommand()).ToString())

    'dAdapt1.InsertCommand = New SqlClient.SqlCommand(insertCmd.ToString(), objCommand.Connection)

    BindData()

    objCommand.Connection.Close()

    objCommand.Connection.Dispose()

    End Sub

     

    im not sure wats going wrong because the record is not being added. Please help!!

  • Re: Inserting a new record into sql db using user-entered information

    11-22-2006, 9:35 PM
    Answer
    • Loading...
    • diehardguy
    • Joined on 06-26-2006, 5:39 PM
    • Belfast
    • Posts 72

    Had a look at your code and I dont really like using dataadadapters for inserts etc when not attached to Gridviews etc. Not much point when we have executenonquery of the command object. Quick, simple and less code. I would also advise using parameterized SQL statements like my example for you below, its safer and if proper validation is present, you should receive near error free pages. Any questions you can email me on damianyoung@onetel.net. When using the below code, just ensure you format the date variables correctly for inserting.

    Also you might want to import these namespaces on your page.

    system.data

    system.data.sqlclient

            REM Collect variables
            Dim empID As Integer = Integer.Parse(CType(FindControl("TextBox8"), TextBox).Text)
            Dim firstName As String = CType(FindControl("TextBox1"), TextBox).Text
            Dim lastName As String = CType(FindControl("TextBox2"), TextBox).Text
            Dim location As String = CType(FindControl("TextBox3"), TextBox).Text
            Dim termDate As Date = CType(FindControl("TextBox4"), TextBox).Text
            Dim hireDate As Date = CType(FindControl("TextBox7"), TextBox).Text
            Dim dept As String = CType(FindControl("TextBox5"), TextBox).Text
            Dim super As String = CType(FindControl("TextBox6"), TextBox).Text
    
            REM Create connection and command objects
            Dim cn As New SqlConnection("Data Source=ELEARN-FRM-BETA;Initial Catalog=StudentPlayGround;Integrated Security=True")
            Dim cmd As New SqlCommand
            cmd.Connection = cn
    
            REM Build our parameterized insert statement
            Dim sql As New StringBuilder
            sql.Append("INSERT INTO Employees ")
            sql.Append("(EmployeeID,FirstName,LatName,Location,HireDate,TerminationDate,Supervisor)")
            sql.Append("VALUES (@empID,@firstName,@lastName,@location,@hireDate,@termDate,@dept,@super)")
            cmd.CommandText = sql.ToString
    
            REM Add parameter values to command
            REM Parameters used to protect DB from SQL injection attacks
            With cmd.Parameters
                .Add("empID", SqlDbType.Int).Value = empID
                .Add("firstName", SqlDbType.VarChar).Value = firstName
                .Add("lastName", SqlDbType.VarChar).Value = lastName
                .Add("location", SqlDbType.VarChar).Value = location
                .Add("hireDate", SqlDbType.DateTime).Value = hireDate
                .Add("termDate", SqlDbType.DateTime).Value = termDate
                .Add("dept", SqlDbType.VarChar).Value = dept
                .Add("super", SqlDbType.VarChar).Value = super
            End With
    
            REM Now execute the statement
    
            cn.Open()
            cmd.ExecuteNonQuery()
            cn.Close()
     
    Hope This helps!
    Damian Young
    MCP
  • Re: Inserting a new record into sql db using user-entered information

    11-22-2006, 9:46 PM
    • Loading...
    • jessjing
    • Joined on 09-26-2006, 8:03 AM
    • Posts 872

    hi,

    I am afraid there is something wrong here

    Dim insertStr As String = "INSERT INTO Employees" + _

     

    "(EmployeeID,FirstName,LatName,Location,HireDate,TerminationDate,Supervisor)" + _

     

    "VALUES (empID,firstName,lastName,location,hireDate,termDate,dept,super)"

    try this

    Dim insertStr As String = "INSERT INTO Employees" + _

     

    "(EmployeeID,FirstName,LatName,Location,HireDate,TerminationDate,Supervisor)" + _

     

    "VALUES (@empID,@firstName,@lastName,@location,@hireDate,@termDate,@dept,@super)"

      Dim PempID As New System.Data.SqlClient.SqlParameter
           PempID.ParameterName = "@empID"
            PempID.Value =empID
           PempID.DbType = Data.DbType.Int32

    and add the other parameters like above

    have a try

     

  • Re: Inserting a new record into sql db using user-entered information

    11-23-2006, 11:45 AM
    • Loading...
    • rox163
    • Joined on 11-22-2006, 8:04 PM
    • Posts 6
    doesnt seem to work still!!
  • Re: Inserting a new record into sql db using user-entered information

    11-23-2006, 4:19 PM
    • Loading...
    • diehardguy
    • Joined on 06-26-2006, 5:39 PM
    • Belfast
    • Posts 72

    Opps, might be a problem in the sql statement. No spaces at the end. Doh!

    Dim sql As New StringBuilder
    sql.Append("INSERT INTO Employees ")
    sql.Append("(EmployeeID,FirstName,LatName,Location,HireDate,TerminationDate,Supervisor) ")
    sql.Append("VALUES (@empID,@firstName,@lastName,@location,@hireDate,@termDate,@dept,@super)")
    cmd.CommandText = sql.ToString

     As you can see above, I forgot to put a space after Supervisor) "), this will create an invalid sql statement when the string is appended.

    If this doesnt correct the code I gave you, please post an error message and you complete code.

    Damian Young
    MCP
Page 1 of 1 (5 items)
Microsoft Communities
Page view counter