-1

Running a method to insert some data into a table EventsManaged using an sql query which returns an error

"incorrect syntax near 'WHERE'"

but I can't see my mistake?

The method is in an EventDAL and being called from an open form. I used breakpoints and checked the correct type of data was being entered- any help?

public static int AddAllToEventsManaged( string areaType, string areaName, double cost, double costPer, int v, int id)            
{    
            using (SqlConnection connection = new SqlConnection(_connectionstring))
            {
                connection.Open();
                string SQLquery1 = string.Format("INSERT INTO EventsManaged (AreaType, AreaName, Cost, CostPer) VALUES ('{0}','{1}','{2}','{3}') WHERE AreaID = '{4}' AND CustomerID = '{5}'", areaType, areaName, cost, costPer, v, id);
                SqlCommand insertProjectCommand = new SqlCommand(SQLquery1, connection);
                int rowsAffected = insertProjectCommand.ExecuteNonQuery();
                connection.Close();
                return rowsAffected;
            }
        }
}
Prakash Palnati
  • 3,231
  • 22
  • 35
Naomi
  • 23
  • 2

2 Answers2

1

Two things to notice:

  • Instead of formatting the command string with the values included, you should use the sql command parameters, that you can add to the Parameters collection of your SqlCommand.
  • You are mixing 2 ways to INSERT things in SQL. You can INSERT ... SELECT ... WHERE or you can INSERT ... VALUES, but the one with VALUES does not allow/need WHERE. I put the links to MySql documentation but I think it is the same for other SQL RDBMS (at leas for SQL Server)
Jorge Y.
  • 1,123
  • 1
  • 9
  • 16
0

I think you want an UPDATE query like this:

string SQLquery1 = string.Format("UPDATE EventsManaged SET AreaType = '{0}', AreaName = '{1}', Cost = '{2}', CostPer = '{3}' WHERE AreaID = '{4}' AND CustomerID = '{5}'", areaType, areaName, cost, costPer, v, id);

This will update your existing row which satisfies the WHERE condition. INSERT statement adds a new row so there is no WHERE clause here. Hope it helped.

Rafichu
  • 70
  • 9