-4
下面的代碼是用於更新數據庫的價值,未處理格式異常用繩子
string updateCom = ("UPDATE Login SET Username = '" + textUsername.Text + "', Password = '" + textPassword.Text + "', Role = '" + comboBox1.Text + "', First_Name = '" + char.Parse(textFirstName.Text) + "', Last_Name = '" + char.Parse(textLastName.Text) + "', Age = " + int.Parse(textAge.Text) + "', Gender = " + char.Parse(textAge.Text) + " WHERE User_ID = " + textUser_ID.Text);
整個事情是封閉在一個嘗試捕捉方法並在調試我得到
「出現FormatException was unhandled「
,它也表示字符串必須是一個字符長。這個未處理的異常只有當我輸入「John Harambe」作爲第一個名字時纔會發生。任何人都可以啓發我正確的格式?
我解決我的問題:
所以我用參數化查詢被評論者之一的建議,這是我到目前爲止的代碼;
updateCom = new SqlCommand("UPDATE Login"
+ "SET Username = @username,"
+ "Password = @password,"
+ "Role = @role,"
+ "First_Name = @firstName,"
+ "Last_Name = @lastName,"
+ "Age = @age,"
+ "Gender = @gender"
+ "WHERE User_ID = @user_ID");
updateCom.Connection = searchCon;
searchCon.Open();
String Username = textUsername.Text;
String Password = textPassword.Text;
String Role = comboBox1.Text;
String First_Name = textFirstName.Text;
String Last_Name = textLastName.Text;
String Age = textAge.Text;
String Gender = textGender.Text;
if (searchCon.State == ConnectionState.Open)
{
updateCom.Parameters.AddWithValue("@username", Username);
updateCom.Parameters.AddWithValue("@password", Password);
updateCom.Parameters.AddWithValue("@role", Role);
updateCom.Parameters.AddWithValue("@firstName", First_Name);
updateCom.Parameters.AddWithValue("@lastName", Last_Name);
updateCom.Parameters.AddWithValue("@age", Age);
updateCom.Parameters.AddWithValue("@gender", Gender);
try
{
updateCom.ExecuteNonQuery();
if (MessageBox.Show("Data UPDATED.", "Admin Power",
MessageBoxButtons.OK, MessageBoxIcon.Information) == DialogResult.OK)
{
searchCon.Close();
}
else
{
if(MessageBox.Show("Data NOT UPDATED", "Admin Power",
MessageBoxButtons.OK, MessageBoxIcon.Information) == DialogResult.OK)
{
return;
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
searchCon.Close();
}
}
,它仍然拋出和未處理的異常
「近 '用戶名' 錯誤語法」。
見'char.Parse(....文本) '。 –
調試時,您還應該看到確切的方法拋出異常。該方法做了一些你不想要的。詳細信息請閱讀其文檔。 – hvd
請使用參數化查詢 https://msdn.microsoft.com/library/bb738521(v=vs.100).aspx http://stackoverflow.com/questions/15246182/sql-update-statement-in-c -尖銳 –