ExecuteNonQuery() throws “Incorrect syntax near th

2019-02-27 23:30发布

问题:

I started learning C# last week and I'm now having trouble with an INSERT sql statement. I used the following code, then I tell you what happens.

private void AddNewUserToDataBase(User user)
{
    string commandText = "INSERT INTO User (firstName,lastName,adress,town,favoriteCurrency) " +
                         "VALUES (@firstName,@lastName,@adress,@town,@favoriteCurrency)";

    using (SqlConnection connection = new SqlConnection(global::Laboratoire1.Properties.Settings.Default.Database1ConnectionString))
    {
        using (SqlCommand command = new SqlCommand())
        {
            command.Connection = connection;
            command.CommandText = commandText;
            command.CommandType = CommandType.Text;

            // je passe les paramètres ici pour éviter les erreurs au niveau du string commande 

            command.Parameters.Add(new SqlParameter("@firstName", user.getFirstName())); // autre façon plus générale
            command.Parameters.Add(new SqlParameter("@lastName", user.getLastName()));
            command.Parameters.Add(new SqlParameter("@adress", user.getAdress()));
            command.Parameters.Add(new SqlParameter("@town", user.getTown()));
            command.Parameters.Add(new SqlParameter("@favoriteCurrency", user.getFavoriteCurrencyId()));

            try
            {
                connection.Open();
                command.ExecuteNonQuery();
                connection.Close();
            }
            catch (SqlException ex)
            {
                MessageBox.Show("Une erreur s'est produite.");
            }
        }
    }
}

My program do not crashes and the exception message box shows up. I've trying to understand my error and changing the syntax of my command.Parameters.Add, but it still doesn't work :/.


After changing the catch block to display the exception instead of swallowing it, it throws:

Incorrect syntax near the keyword 'User'

回答1:

You've got a table with the name "User", but that's a reserved keyword.

You could rename the table, or enclose it in brackets when you reference it:

string commandText = "INSERT INTO [User] (firstName ...


回答2:

Change the table name from "User" to something else because User is a reserved keyword that cannot be used again, so if you use any other name for table the code will work fine example:-

create table User1(firstName varchar(20),lastName varchar(20),adress varchar(20),town varchar(20),favoriteCurrency int)