1

我正在尝试使用下面的代码从 asp.net 页面将数据插入本地数据库,但我不断收到此错误

“关键字‘用户’附近的语法不正确”

 protected void Button1_Click(object sender, EventArgs e)
    {
        SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["RegConnectionString"].ConnectionString);
        con.Close();
        string inse = "insert into user (username, password, emailadd, fullname, country) values(@username, @password, @emailadd, @fullname, @country) ";
        SqlCommand insertuser = new SqlCommand(inse, con);
        insertuser.Parameters.AddWithValue("@username",TextBoxFA.Text);
        insertuser.Parameters.AddWithValue("@password", TextBoxEA.Text);
        insertuser.Parameters.AddWithValue("@emailadd", TextBoxRPW.Text);
        insertuser.Parameters.AddWithValue("@fullname", TextBoxPW.Text);
        insertuser.Parameters.AddWithValue("@country",DropDownList1.SelectedItem.ToString());

        try
        {
            insertuser.ExecuteNonQuery();
            con.Close();
            Response.Redirect("login.aspx");
        }
        catch (Exception ex)
        {
            Response.Write("<b>something really bad happened.....Please try again</b> ");
        }
    }
4

3 回答 3

6

恭喜您使用了参数化查询!

user是一个关键字,所以用方括号括起来,比如[user].

一些评论:

  1. 您应该使用usingfor 连接和命令来自动处理未使用的资源
  2. 第一个con.Close();没有意义,可以删除。相反,您需要致电con.Open();
  3. finally在您关闭连接的位置创建一个块。目前发生异常时不会关闭。

话虽如此,您的代码将显示为:

using (SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["RegConnectionString"].ConnectionString))
{
    con.Open();

    string inse = "insert into [user] (username, password, emailadd, fullname, country) values(@username, @password, @emailadd, @fullname, @country)";
    using (SqlCommand insertuser = new SqlCommand(inse, con))
    {
        insertuser.Parameters.AddWithValue("@username",TextBoxFA.Text);
        insertuser.Parameters.AddWithValue("@password", TextBoxEA.Text);
        insertuser.Parameters.AddWithValue("@emailadd", TextBoxRPW.Text);
        insertuser.Parameters.AddWithValue("@fullname", TextBoxPW.Text);
        insertuser.Parameters.AddWithValue("@country",DropDownList1.SelectedItem.ToString());

        try
        {
            insertuser.ExecuteNonQuery();
            Response.Redirect("login.aspx");
        }
        catch (Exception ex)
        {
            Response.Write("<b>something really bad happened.....Please try again</b> ");
        }
        finally
        {
            con.Close();
        }
    }
}
于 2013-01-16T14:31:21.040 回答
5

尝试将单词 user 括在方括号中。我相信 user 是保留关键字。

IE

string inse = "insert into [user] (username, password, emailadd, fullname, country) values(@username, @password, @emailadd, @fullname, @country) ";

您在该代码中还有其他几个问题,但是没有将用户放在方括号中是导致您看到的错误消息的原因。

于 2013-01-16T14:30:18.733 回答
1

user是一个保留关键字,因此您只需将其括在方括号中以明确表示您的意思是名为“User”的对象:

insert into [user]
于 2013-01-16T14:30:52.917 回答