如何处理关键字用户

时间:2019-04-27 13:01:36

标签: c# sql-server

我正在使用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");
    }
}

代码似乎还可以,但出现错误

  

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

请帮助我-谢谢

2 个答案:

答案 0 :(得分:3)

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

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

顺便说一句,VALUES是您写的VALUSE。并且最好在INSERT语句中明确列出目标列,例如

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

这样,即使表中的列数或顺序由于某种原因发生了变化,该语句仍然可以工作。

答案 1 :(得分:0)

在下面的行中,您拼错了 VALUES ,而不是键入了 VALUSE

using (SqlCommand com = new SqlCommand("INSERT INTO user VALUSE(@user_id, @name, @fathername, @username, @password, @email, @gender, @dob, @date_of_join, @contact, @address)", con))