views:

313

answers:

3

Dear Sir, I wrote code to insert textbox data into sql database, my code working properly but when I open the table no data was added, my code given below, help me...

Private Sub save_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles save.Click


    Dim connetionString As String
    Dim connection As SqlConnection
    Dim adapter As New SqlDataAdapter
    Dim tabl As New DataTable
    Dim sql As String


    connetionString = "Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\Database1.mdf;Integrated Security=True;User Instance=True"
    connection = New SqlConnection(connetionString)
    Try
        sql = "insert into model (no,fistname,lastname) values('" & TextBox1.Text & "','" & TextBox2.Text & "','" & TextBox3.Text & "')"
        adapter.InsertCommand = New SqlCommand(sql, connection)
        connection.Open()

        adapter.InsertCommand.ExecuteNonQuery()

        MsgBox("Row inserted !! ")
        connection.Close()

    Catch ex As Exception
        MsgBox(ex.ToString)
        connection.Close()
    End Try

End Sub
+1  A: 
Pointy
+9  A: 

Don't use a Data Adapter. That just over-complicates things in this case. Try:

Using SqlConnection connection = new SqlConnection(connectionString)

    sql = "insert into model (no, firstname, lastname)" & _ 
        " values (@val1, @val2, @val3)"

    Dim SqlCommand command = new SqlCommand(sql, connection)

    command.Parameters.Add("val1", TextBox1.Text)
    command.Parameters.Add("val2", TextBox2.Text)
    command.Parameters.Add("val3", TextBox3.Text)

    command.ExecuteNonQuery()

End Using

This way, you don't have to worry about the Adapter (since you're not using a GridView) and you're using parameterized queries rather than dynamically building SQL (which allows for SQL Injection attacks).

Justin Niessner
+1 for informing about SQL Injection attacks
Searock
-1 for dragging SQL injection into an unrelated question, +1 for a working answer and +1 for data adapters over-complicating things :)
Andomar
Besides SQL injection, it might also be worth mentioning error checking/trapping...?
Philip Kelley
I only posted a subset of his original code. He does have everything wrapped in a Try/Catch block. Although it would be worth mentioning that if he doesn't use a Using block around the call...he should add a finally to the try/catch to Dispose of everything.
Justin Niessner
+1  A: 

How do you confirm that the data was not inserted?

I suspect your issue may be related to using User Instances of SQL Express. See http://msdn.microsoft.com/en-us/library/bb264564%28SQL.90%29.aspx