我想使用 C# 更新数据库 im 上的用户信息。 这是我的代码,它不起作用,也没有给我任何错误。
protected void Page_Load(object sender, EventArgs e)
{
lbldisplay.Text = "<b><font color=BLUE>" + "WELLCOME:: " + "</font>" + "<b><font color=white>" + Session["Name"] + "</font>";
SqlConnection con = new SqlConnection("Data Source=STUDENT-PC;Initial Catalog=webservice_BuyBid;Integrated Security=True");
}
protected void btnLogOut_Click(object sender, EventArgs e)
{
//this will redirect the page to the home.aspx page.
Response.Redirect("Home.aspx");
}
protected void btnUpdate_Click(object sender, EventArgs e)
{
//creating a new connection to the database
SqlConnection con = new SqlConnection("Data Source=STUDENT-PC;Initial Catalog=BuyBid;Integrated Security=True;Asynchronous Processing=True;");
con.Open();
//creates a new sqlcommand to update the buyer's information to the Database.
SqlCommand cmd = new SqlCommand("UPDATE BUYER SET Name = @Name,Surname = @Surname,Email =@Email,CellNumber =@CellNumber", con);
con.Open();
cmd.Parameters.AddWithValue("@Name", txtNameUpdate.Text);
cmd.Parameters.AddWithValue("@Surname", txtSurnameUpdate.Text);
cmd.Parameters.AddWithValue("@Email", txtemailUpdate.Text);
cmd.Parameters.AddWithValue("@CellNumber", txtCellUpdate.Text);
int rows = cmd.ExecuteNonQuery();
con.Close();
最佳答案
您的问题是您正在打开一个连接(这是正确的),但随后您又打开了它。
这就是更新没有发生的原因。此外,您无需在 finally 语句中关闭连接。出于此目的,它不是必需的。
同时你正在执行更新语句,所以请确保你给它一个条件来更新特定的记录。
我已经适本地编辑了您的代码,这应该可以解决您的问题: (久经考验)
protected void btnUpdate_Click(object sender, EventArgs e)
{
try
{
//creating a new connection to the database
SqlConnection con = new SqlConnection("Data Source=STUDENT- PC;Initial Catalog=BuyBid;Integrated Security=True;Asynchronous Processing=True;");
con.Open();
//creates a new sqlcommand to update the buyers information to the Database.
SqlCommand cmd = new SqlCommand("UPDATE BUYER SET Name = @Name,Surname = @Surname,Email =@Email,CellNumber =@CellNumber WHERE Email =@Email", con);
//con.Open();
cmd.Parameters.AddWithValue("@Name", txtNameUpdate.Text);
cmd.Parameters.AddWithValue("@Surname", txtSurnameUpdate.Text);
cmd.Parameters.AddWithValue("@Email", txtemailUpdate.Text);
cmd.Parameters.AddWithValue("@CellNumber", txtCellUpdate.Text);
cmd.BeginExecuteNonQuery();
}
catch (Exception e)
{
Console.WriteLine("Exception occured: " + e.StackTrace);
}
finally
{
// close connection if it is still open
// editing from phone so just writting the comments here
}
}
让我知道结果。
关于c# - 更新数据库中的信息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29695153/