Skip to main content
 首页 » 编程设计

c#之ExecuteNonQuery() 抛出 "Incorrect syntax near the keyword ' 用户'”

2024年02月06日16kenshinobiy

我上周开始学习 C#,但现在遇到了 INSERT sql 语句的问题。我使用了下面的代码,然后我告诉你会发生什么。

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."); 
            } 
        } 
    } 
} 

我的程序没有崩溃,也没有出现异常消息框。我试图了解我的错误并更改我的 command.Parameters.Add 的语法,但它仍然不起作用:/。


将 catch block 更改为显示异常而不是吞下它后,它抛出:

Incorrect syntax near the keyword 'User'

请您参考如下方法:

您有一个名为“User”的表,但它是一个 reserved keyword .

您可以重命名表格,或在引用时将其括在括号中:

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