简体   繁体   中英

ExecuteNonQuery() throws “Incorrect syntax near the keyword 'User'”

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'

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 ...

将表名从“ User”更改为其他名称,因为User是不能再次使用的保留关键字,因此,如果对表使用任何其他名称,该代码将可以正常工作,例如:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM