SQL error: Incorrect syntax near the keyword 'User'

BlueBird picture BlueBird · May 21, 2011 · Viewed 79.2k times · Source

I am using SQL to insert data to SQL Database file using C# as follows.

    String cs = System.Configuration.ConfigurationManager.ConnectionStrings["connection1"].ConnectionString;
    SqlConnection conn = new SqlConnection(cs);
    String sql = "INSERT INTO User (login, password, status) " + 
            "VALUES (@login, @password, @status)";
    SqlCommand comm = new SqlCommand(sql, conn);

    comm.Parameters.Add("@login", System.Data.SqlDbType.VarChar);
    comm.Parameters.Add("@password", System.Data.SqlDbType.VarChar);
    comm.Parameters.Add("@status", System.Data.SqlDbType.Bit);

    try
    {
        conn.Open();
        Console.WriteLine(conn.ToString());
        comm.ExecuteNonQuery();
        conn.Close();
        return true;
    }
    catch (Exception ex)
    {
        throw (ex);
    }
    finally
    {
        conn.Close();
    }

I am getting the following error when command is executing.

Incorrect syntax near the keyword 'User'.: INSERT INTO User (login, password, status) VALUES (@login, @password, @status)

How can I solve this please?

edit: missed parameter values added..

    comm.Parameters["@login"].Value = this.Username;
    comm.Parameters["@password"].Value = this._password;
    comm.Parameters["@status"].Value = this.Status;

Answer

Marc Gravell picture Marc Gravell · May 21, 2011

User is a reserved keyword, so you must use square brackets to make it explicit that you mean the object named "User" it, i.e. use [User] instead of User.