'Invalid SQL statement; expected 'DELETE', 'INSERT', 'PROCEDURE', 'SELECT', or 'UPDATE'

Hi I have an invalid sql statement error. This is my code:

Imports System.Data.OleDb   'For OleDbConnection 
Imports System.Data         'For ConnectionState 


Public Class WebForm1

    Inherits System.Web.UI.Page

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

    End Sub

    Protected Sub btnInsert_Click(sender As Object, e As EventArgs) Handles btnInsert.Click
        '1 declare the variables
        Dim strName As String = txtName.Text
        Dim strAddress As String = txtAddress.Text


        '2. creates a new connection to your DB.
        Dim conn As New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source='C:\Users\GT\Documents\Database11.accdb'")
        If conn.State = ConnectionState.Open Then
            conn.Close()
        End If

        '3. open the connection to your DB. 
        conn.Open()

        '4. assign your SQL statement into sqlString variable. 
        Dim sqlString As String
        sqlString = "INSERT INTO tblStuInfo (stuName, stuAddress) VALUES ('" & strName & "' , '" & strAddress & "')"

        '5. create a new command that links your SQL statement with your connection. 
        Dim sqlcommand As New OleDbCommand(sqlString, conn)

        '6. execute your command.
        sqlcommand.ExecuteNonQuery()
    End Sub
End Class

What is the problem? The path of the database and the table name of the DB is correct. Please help!



Solution 1:[1]

try to replace

sqlString = "INSERT INTO tblStuInfo (stuName, stuAddress) VALUES ('"
    & strName & "' , '" & strAddress & "')"

with

sqlString = "INSERT INTO tblStuInfo (stuName, stuAddress) VALUES ('"
    & strName.Replace("'", "''") & "' , '" & strAddress.Replace("'", "''") & "')"

this should solve any SQL injection issue, that happen when your string contain the ' character.

Anyway, I think you should add (or use) a key in the underlying table, otherwise how are you going to get these values back?

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Peter Lang