且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

的ExecuteNonQuery()抛出"近关键字'用户'"语法不正确;

更新时间:2022-10-23 18:00:27

您已经有了一个名为用户一表,但这是保留关键字一个



您可以重命名表,或将其包含在方括号当你引用它:

 字符串的CommandText =INSERT [用户](名字... 


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