如何将数据库查询返回的值与windows窗体中的值进行比较

时间:2013-03-26 16:29:11

标签: c# winforms

我想检查我的数据库中是否存在电子邮件,然后根据返回的值执行furthur语句.....我的代码如下.....

private void deleterecordbutton_Click(object sender, EventArgs e)
        {
            if (deleterecordtextBox.Text != "")
            {
                MyOleDbConnection.Open();
                string vsql = string.Format("delete from login where Email='{0}'", deleterecordtextBox.Text);
                OleDbCommand vcom = new OleDbCommand(vsql, MyOleDbConnection.vcon);
                vcom.ExecuteNonQuery();
                MessageBox.Show("Record deleted successfully!!");
                MyOleDbConnection.Close();
                deleterecordtextBox.Clear();
                this.Close();
                this.ReferToLogindb.Show();
            }
            else
            {
                MessageBox.Show("No record selected");
            }
        }

3 个答案:

答案 0 :(得分:0)

在数据库上运行查询,该查询计算包含电子邮件地址的行数,并对结果执行条件语句以检查其是否为1或更大,如果是,则执行其他代码

答案 1 :(得分:0)

如果您只想知道在执行查询后是否删除了记录,则从ExecuteNonQuery获取返回值。它返回受命令影响的行数。

如果没有与您的查询匹配的记录,则返回值将为零 See MSDN docs

int recordsDeleted = vcom.ExecuteNonQuery();
if(recordsDeleted != 0)
   .....
else
   ....

顺便说一下,你的代码有一个潜在的问题叫做Sql Injection,你可能会遇到连接未正确关闭的问题。我建议改为:

using(OleDbConnection oleConn = GetConnection())
{
    oleConn.Open();
    string vsql = "delete from login where Email=@mail";
    OleDbCommand vcom = new OleDbCommand(vsql, oleConn);
    vcom.Parameters.AddWithValue("@mail", deleterecordtextBox.Text);
    int recordsDeleted = vcom.ExecuteNonQuery();
    if(recordsDeleted != 0)
        MessageBox.Show("Record deleted successfully!!");
    else
        MessageBox.Show("Record not found!");
 }
 deleterecordtextBox.Clear();
 ......

答案 2 :(得分:0)

除了指定的所有其他建议外, 改变:

if (deleterecordtextBox.Text != "")

为:

if (deleterecordtextBox.Text !=string.Empty)