Search code examples
asp.netdatabasesqlexception

ASP.NET SqlConnection - Exception - Incorrect Syntax


I have the following code and this runs I get an SqlException error saying invalid syntax near the keyword 'User'. Any ideas? Guessing it's something simple but I just can't spot it.

    string insertStmt =
       "INSERT INTO User (UserName) VALUES(@UserName)";

    using (SqlConnection _con = new SqlConnection(myConnectionString))
    using (SqlCommand _cmd = new SqlCommand(insertStmt, _con))
    {
        _cmd.Parameters.Add("@UserName", SqlDbType.NVarChar).Value = UserName;

        try
        {
            _con.Open();
            _cmd.ExecuteNonQuery();
            _con.Close();
        }
        catch (Exception x)
        {
           // output exception
        }
    }

Solution

  • You need to escape user probably since it's a reserved word in sql.

    Try this

    string insertStmt =
       "INSERT INTO [User] (UserName) VALUES(@UserName)";