讓我們先從一些基礎知識:
這裏是如何看的代碼aspx頁面:
private void btnUpdatePersonalDetails_Click(object sender, EventArgs e)
{
if (rndMale.Checked == true)
{
gender = "Male";
}
else
{
if (rndFemale.Checked == true)
{
gender = "Female";
}
}
PersonalDetails personDetails = new PersonalDetails();
personalDetails.UpdateDetails(txtFirstName.Text, txtLastName.Text, txtAge.Text, txtHeight.Text,txtAverageRestingHeartRate.Text, txtContactNumber.Text, txtAddress.Text, gender, GlobalUserName.username);
}
這裏是Business
對象類 - >這裏我會使用重命名的列。您應該在數據庫中重命名您的列。
public void UpdateDetails(string firstName, string lastName, string age, string height, string avgHeartRate, string contactNumber, string address, string gender, string userName)
{
SqlCommand cmd = new SqlCommand(@"
UPDATE
PersonalDetails
SET
FirstName = @FirstName,
LastName = @LastName,
Age = @Age,
Height = @Height,
AvgHeartRate = @AvgHeartRate,
ContactNumber = @ContactNumber
Address = @Address,
Gender = @Gender
WHERE
UserName = @UserName
");
cmd.Parameters.AddWithValue("@FirstName", firstName);
cmd.Parameters.AddWithValue("@LastName", lastName);
cmd.Parameters.AddWithValue("@Age", age);
cmd.Parameters.AddWithValue("@Height", height);
cmd.Parameters.AddWithValue("@AvgHeartRate", avgHeartRate);
cmd.Parameters.AddWithValue("@ContactNumber", contactNumber);
cmd.Parameters.AddWithValue("@Address", address);
cmd.Parameters.AddWithValue("@Gender", gender);
cmd.Parameters.AddWithValue("@UserName", userName);
SqlManager.ExecuteNonQuery(cmd);
}
這裏是SqlManager
類兩種方法:
public static int ExecuteNonQuery(SqlCommand cmd)
{
SqlConnection conn = GetSqlConnection(cmd);
try
{
return cmd.ExecuteNonQuery();
}
catch
{
throw;
}
finally
{
conn.Close();
}
}
public static SqlConnection GetSqlConnection(SqlCommand cmd)
{
if (cmd.Connection == null)
{
SqlConnection conn = new SqlConnection(ConnectionString);
conn.Open();
cmd.Connection = conn;
return conn;
}
return cmd.Connection;
}
如果你寫列名正確,這將更新您的個人資料沒有問題。我在這個問題中編寫了基本的數據訪問層:checking user name or user email already exists。你可以檢查它,如果你想。
你真的有一個名爲'Height(cm)'的列嗎? – 2014-12-27 13:27:28
如果你解釋它應該做什麼,以及收到什麼錯誤消息(如果有),它會有所幫助。 – 2014-12-27 13:27:35
哇,這真的是如何不在C#中執行SQL。它很容易SQL注入。很容易有人不會選擇性別。這太糟糕了。你有一個字段名稱「高(釐米)」?哇。真。哇。 – nvoigt 2014-12-27 13:27:58