我试图使用下面的代码从asp.net页面插入数据到本地数据库,但我一直收到此错误
“关键字'user'附近的语法不正确”
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> ");
}
}
答案 0 :(得分:6)
祝贺您使用参数化查询!
user
是关键字,因此请将其包含在方括号中,例如[user]
。
一些意见:
using
连接和命令自动处理未使用的资源con.Close();
没有意义,可以删除。相反,您需要致电con.Open();
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();
}
}
}
答案 1 :(得分:5)
尝试将用户包装在方括号中。我相信用户是一个保留的关键字。
即
string inse = "insert into [user] (username, password, emailadd, fullname, country) values(@username, @password, @emailadd, @fullname, @country) ";
您在该代码中还有其他几个问题,但不会将用户放在方括号中是导致您看到的错误消息的原因。
答案 2 :(得分:1)
user
是reserved keyword,因此您只需将其包装在方括号中,以明确表示您指的是名为“User”的对象:
insert into [user]