Jarobe Bernardo
Jarobe Bernardo

Reputation: 75

error in Inserting data in database

Problem : Inserting data into database.

Error:

SQLException was unhandled by the user

Incorrect Syntax near the keyword 'User'

the one the I put arrow is the line that is highlighted seems it was the error i'm not sure.

Imports System.Web
Imports System.Web.UI
Imports System.Web.UI.WebControls
Imports System.Data.SqlClient
Imports System.Configuration

Partial Public Class _Default
    Inherits System.Web.UI.Page

    Dim con As New SqlConnection(ConfigurationManager.ConnectionStrings("ConnectionString").ConnectionString)

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        con.Open()
    End Sub

    Protected Sub addBTN_Click(ByVal sender As Object, ByVal e As EventArgs) Handles addBTN.Click
    Dim cmd As New SqlCommand("insert into User (Name, Gender, Age) values ('" & nameTB.Text & "', '" & genderTB.Text & "', '" & ageTB.Text & "')", con)
    cmd.ExecuteNonQuery()  <------------------------------
    con.Close()
    nameTB.Text = ""
    genderTB.Text = ""
    ageTB.Text = ""

End Sub
End Class

Upvotes: 0

Views: 50

Answers (2)

dovid
dovid

Reputation: 6452

User is a reserved word. Enclose the word with square brackets:

 Dim cmd As New SqlCommand("insert into [User] (Name, Gender, Age) values ('" & nameTB.Text & "', '" & genderTB.Text & "', '" & ageTB.Text & "')", con)

Source: https://stackoverflow.com/a/6082422/1271037

Upvotes: 0

Fred
Fred

Reputation: 5808

User is a reserved word so needs to be in square brackets. Your query is open to SQL injection so needs to be parameterized. I would advise opening the connection just before you need it. Also use the Using statement will take care of closing and disposal for you.

Using con As New SqlConnection(ConfigurationManager.ConnectionStrings("ConnectionString").ConnectionString)
     Using cmd As New SqlCommand("insert into [User] (Name, Gender, Age) values (@nameTB, @genderTB,@ageTB)", con)
        cmd.Parameters.AddWithValue("@nameTB", nameTB.Text)
        cmd.Parameters.AddWithValue("@genderTB", genderTB.Text)
        cmd.Parameters.AddWithValue("@ageTB", ageTB.Text)
        cmd.CommandType = CommandType.Text
        con.Open()
        cmd.ExecuteNonQuery()
        nameTB.Text = ""
        genderTB.Text = ""
        ageTB.Text = ""
    End Using
End Using

Upvotes: 2

Related Questions