首页 > 解决方案 > 如何处理关键字用户附近语法错误的错误

问题描述

我正在将学校管理系统构建为 C# 中的 Windows 应用程序。我使用了本地数据库和 Visual Studio 2017;我尝试将数据插入表中:

SqlConnection con = new SqlConnection(@"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\Users\zar_m\source\repos\SIS2\SIS2\SISDB.mdf;Integrated Security=True");

con.Open();

string sql_Text = "INSERT INTO user Values(@user_id,@name,@fathername,@username,@password,@email,@gender,@dob,@date_of_join,@contact,@address)";
//(user_id, name, fathername, username, password, email, gender, dob, date_of_join, contact, address)

using (SqlCommand com = new SqlCommand("INSERT INTO user VALUSE(@user_id, @name, @fathername, @username, @password, @email, @gender, @dob, @date_of_join, @contact, @address)", con))
{
    com.Parameters.AddWithValue("@user_id", user_idTextBox.Text);
    com.Parameters.AddWithValue("@name", nameTextBox.Text);
    com.Parameters.AddWithValue("@fathername", fathernameTextBox.Text);
    com.Parameters.AddWithValue("@username", usernameTextBox.Text);
    com.Parameters.AddWithValue("@password", passwordTextBox.Text);
    com.Parameters.AddWithValue("@email", emailTextBox.Text);
    com.Parameters.AddWithValue("@gender",genderTextBox.Text);
    com.Parameters.AddWithValue("@dob", dobTextBox.Text);
    com.Parameters.AddWithValue("@date_of_join", date_of_joinTextBox.Text);
    com.Parameters.AddWithValue("@contact", contactTextBox.Text);
    com.Parameters.AddWithValue("@address", addressTextBox.Text);

    int i = com.ExecuteNonQuery();

    con.Close();

    if (i != 0)
    {
        MessageBox.Show(i + "Data Saved");
    }
}

代码似乎没问题,但我得到一个错误

关键字用户附近的语法不正确

请帮助我-谢谢

标签: c#sql-server

解决方案


如果关键字用作标识符,如表或列名,则必须用引号引起来。user即在您的查询中放置方括号。

INSERT INTO [user] VALUES (@user_id, @name, @fathername, @username, @password, @email, @gender, @dob, @date_of_join, @contact, @address)

顺便说一句,它是VALUES,你写的VALUSEINSERT在语句中明确列出目标列是个好主意,例如

INSERT INTO [user] (id, name, ...) VALUES ...

这样即使表中列的数量或顺序由于某种原因发生变化,该语句仍然有效。


推荐阅读