Zeeshan Rizvi
Zeeshan Rizvi

Reputation: 57

Why I get Syntax error in INSERT INTO statement?

protected void btnUpload_Click(object sender, EventArgs e)
{
    if (FileUpload1.PostedFile != null)
    {
        string FileName = Path.GetFileName(FileUpload1.PostedFile.FileName);
        //Save files to disk
        FileUpload1.SaveAs(Server.MapPath("" + FileName));

        //Add Entry to DataBase
        String strConnString = System.Configuration.ConfigurationManager.ConnectionStrings["conString"].ConnectionString;

        OleDbConnection con = new OleDbConnection(strConnString);

        string strQuery = "INSERT INTO image([FileName],[FilePath],[AlbumName]) Values(@FN, @FP, @AN)";

        OleDbCommand cmd = new OleDbCommand(strQuery);

        cmd.Parameters.AddWithValue("@FN", FileName);
        cmd.Parameters.AddWithValue("@FP", "images/" + FileName);
        cmd.Parameters.AddWithValue("@AN", txtAlbumname.Text.ToString());

        cmd.CommandType = CommandType.Text;
        cmd.Connection = con;
        try
        {
            con.Open();
            cmd.ExecuteNonQuery();
        }

        catch (Exception ex)
        {
            Response.Write(ex.Message);
        }

        finally
        {
            con.Close();
            con.Dispose();
        }
    }
}
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
    string var = DropDownList1.SelectedItem.ToString();
    txtAlbumname.Text = var.ToString();
}
}

I Have tried almost everything , but this error keeps on coming. I have put on the brackets aswell incase of reserved words but still this error is showing

Upvotes: 1

Views: 98

Answers (2)

Gord Thompson
Gord Thompson

Reputation: 123409

IMAGE is a reserved word in Access SQL so to use it as a table name you must also enclose it in square brackets:

string strQuery = "INSERT INTO [image] ([FileName], ...

Upvotes: 0

Shekhar Pankaj
Shekhar Pankaj

Reputation: 9125

The OLE DB .NET Provider does not support named parameters for passing parameters to an SQL statement or a stored procedure called by an OleDbCommand when CommandType is set to Text. In this case, the question mark (?) placeholder must be used. For example:

SELECT * FROM Customers WHERE CustomerID = ?

Therefore, the order in which OleDbParameter objects are added to the OleDbParameterCollection must directly correspond to the position of the question mark placeholder for the parameter in the command text.

For Example

OleDbCommand command = new OleDbCommand(queryString, connection);
command.CommandText = 
    "SELECT CustomerID, CompanyName FROM Customers WHERE Country = ? AND City = ?";
command.Parameters.Add(parameters);

for (int j=0; j<parameters.Length; j++)
{
    command.Parameters.Add(parameters[j]) ;
}

for reference .. MSDN

Upvotes: 1

Related Questions