-1

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

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");
            }
        }
4

3 回答 3

0

run a query on the database that counts the number of rows that contain the email address and do a conditional statement on the result to check if its 1 or greater and if so do your other code

于 2013-03-26T16:33:16.250 回答
0

If you want just to know if a record has been deleted AFTER your query execute, then get the return value from ExecuteNonQuery. It returns the number of rows affected by your command.

If there is no record that matches your query the return value will be zero
See MSDN docs

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

By the way, your code has a potential problem called Sql Injection and you could have problems with connection not closed correctly. I suggest to change to:

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();
 ......
于 2013-03-26T16:33:24.243 回答
0

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

if (deleterecordtextBox.Text != "")

至:

if (deleterecordtextBox.Text !=string.Empty)
于 2013-03-26T16:57:37.480 回答