[英]SQL Database If-Else statement
private void btnChange_Click(object sender, EventArgs e)
{
con.Open();
SqlCommand cmd = con.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "update Customer set MembershipPoint='" + textMembershipPoint.Text + "' where NameCustomer='" + textNameCustomer.Text + "'";
cmd.ExecuteNonQuery();
if (cmd.ExecuteScalar() != null)
{
textMembershipPoint.Text = Convert.ToString(cmd.ExecuteScalar());
}
else if (cmd.ExecuteScalar() != )
{
MessageBox.Show("Invalid Name of Customer.");
}
else if (cmd.ExecuteScalar() != )
{
MessageBox.Show("Invalid Membership Point. Only Number Allowed.");
}
else
{
MessageBox.Show("Membership Point is changed.");
}
con.Close();
display_data();
}
我有一个名为Customer
的数据库表, NameCustomer
包含ID_Customer
、 NameCustomer
和MembershipPoint
列。
当客户输入不在Customer
表中的名称时,输出将显示“Invalid Name of Customer.”。
如果客户输入无效的 MembershipPoint,输出将显示“Invalid Membership Point. Only Number Allowed.”。
如果一切正常,则输出将显示“Membership Point is changed.”。
谁能告诉我我需要为 if else 语句做些什么才能实现这一目标?
首先,您必须学习使用参数化查询以避免#1 漏洞——SQL 注入! 这样做 -总是- 没有例外。
其次 - 现在,您正在多次执行UPDATE
语句,这非常糟糕......只需执行一次,记录结果,然后仅根据结果进行推理 - 不要多次执行 SQL 命令。
所以尝试这样的事情:
private void btnChange_Click(object sender, EventArgs e)
{
// check if the membership points text is a valid INT or not
int membershipPoints = 0;
if (!int.TryParse(textMembershipPoint.Text, out membershipPoints))
{
MessageBox.Show("Invalid Membership Point. Only Number Allowed.");
return;
}
// use a properly parametrized query
string updateQuery = "UPDATE dbo.Customer SET MembershipPoint = @Points WHERE NameCustomer = @CustomerName;";
// put your SqlCommand into a proper "using" block
using (SqlCommand cmd = new SqlCommand (updateQuery, con))
{
// define the parameters and set their values
cmd.Parameters.Add("@Points", SqlDbType.Int).Value = membershipPoints;
cmd.Parameters.Add("@CustomerName", SqlDbType.VarChar, 100).Value = textNameCustomer.Text;
// open connection, execute UPDATE, record number of rows updated, close connection
con.Open();
int rowsUpdated = cmd.ExecuteNonQuery();
con.Close();
// now reason just on the result
if (rowsUpdated > 0)
{
// some rows were updated --> success
MessageBox.Show("Success - rows updated");
}
else
{
// no rows were updated -->
MessageBox.Show("No rows updated - most likely invalid customer name");
}
}
display_data();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.