Some Help on Insert

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • 1druid1
    New Member
    • Mar 2007
    • 5

    #1

    Some Help on Insert

    Hi All

    I have the following code..

    Basically I have two fields on my form Fname and Sname and I want to insert the contents of these two text field into my SQL databse.. But I keep on getting the following error.

    "Error executing SQL: The name 'Firstname' is not permitted in this context. Only constants, expressions, or variables allowed here. Column names are not permitted.

    Can anyone help.


    Code:
    Private Sub btnExecute_Click(ByVal sender As Object, _
     ByVal e As System.EventArgs) Handles btnExecute.Click
            Dim oCmd As SqlClient.SqlCommand
            Dim strConn As String
            Dim Firstname As String
            Dim secondname As String
    
            Try
                           strConn &= "Data Source=MyServer;"
                strConn &= "Initial Catalog=MyDatabase;"
                strConn &= "User ID=MyUsername;"
                strConn &= "Password=MyPassword;"
    
                            oCmd = New SqlClient.SqlCommand()
                            oCmd.Connection = _
                            New SqlClient.SqlConnection(strConn)
                           oCmd.Connection.Open()
                           Firstname = Fname.Text
                            secondname = Sname.Text
    
                oCmd.CommandText = String.Format("Insert into Information(First_Name, Last_Name) Values  ([Firstname], [Secondname])")
                            txtRows.Text = _
                 oCmd.ExecuteNonQuery().ToString()
    
                MessageBox.Show("SQL statement succeeded", _
                 "btnExecute_Click()")
    
                
                oCmd.Connection.Close()
    
            Catch oExcept As Exception
                txtRows.Text = 0.ToString()
                MessageBox.Show("Error executing SQL: " & _
                 oExcept.Message, "btnExecute_Click()")
    
            End Try
        End Sub
    
    End Class
    Regards

    Douglas Bell
  • avkdsiva
    New Member
    • Mar 2007
    • 23

    #2
    Try this:

    oCmd.CommandTex t = String.Format(" Insert into Information(Fir st_Name, Last_Name) Values ( '" + Firstname + "', '" + Secondname + "')")

    or

    oCmd.CommandTex t = String.Format(" Insert into Information(Fir st_Name, Last_Name) Values ('{0}','{1}'", Firstname , Secondname)

    Comment

    • 1druid1
      New Member
      • Mar 2007
      • 5

      #3
      Originally posted by avkdsiva
      Try this:

      oCmd.CommandTex t = String.Format(" Insert into Information(Fir st_Name, Last_Name) Values ( '" + Firstname + "', '" + Secondname + "')")

      or

      oCmd.CommandTex t = String.Format(" Insert into Information(Fir st_Name, Last_Name) Values ('{0}','{1}'", Firstname , Secondname)

      Perfect Cheers for the help..

      Comment

      Working...