[英]inserting data into database using asp.net c#
我正在嘗試使用以下代碼從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> ");
}
}
祝賀您使用參數化查詢!
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();
}
}
}
嘗試將用戶一詞包裝在方括號中。 我相信用戶是保留關鍵字。
即
string inse = "insert into [user] (username, password, emailadd, fullname, country) values(@username, @password, @emailadd, @fullname, @country) ";
您在該代碼中還有其他幾個問題,但是未將用戶放在方括號中是導致您看到的錯誤消息的原因。
user
是一個保留關鍵字 ,因此您只需將其包裝在方括號中即可清楚表明您的意思是名為“ User”的對象:
insert into [user]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.