簡體   English   中英

單擊按鈕從Access數據庫中刪除特定記錄

[英]Deleting specific record from Access database on button click

我有一個包含9個字符的字符串,例如LON052012(來自倫敦23.05.2012。-day.month.year。)。 我想從Access中的表中刪除所有記錄,其中所有城市均以該字符串中的前三個字母開頭,並具有這些月份和年份(05.2007。)。

這是功能:

private void button2_Click(object sender, EventArgs e)
    {
        if (textBox1.Text != "")
        {
            try
            {
                string sTown, s1, s2;
                sTown = textBox1.Text.Substring(0, 3);
                s1 = textBox1.Text.Substring(3, 2);
                s2 = textBox1.Text.Substring(5);

                string sDelete = "DELETE * FROM Country WHERE Town LIKE @p1 and month(TownDate) = @p2 and year(TownDate) = @p3";
                OleDbCommand komDelete = new OleDbCommand(sDelete, connection);
                komDelete.Parameters.AddWithValue("@p1", sTown + "*");
                komDelete.Parameters.AddWithValue("@p2", s1);
                komDelete.Parameters.AddWithValue("@p3", s2);
                connection.Open();
                komDelete.ExecuteNonQuery();
                MessageBox.Show("Deleted");
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
            finally
            {
                connection.Close();
            }
        }
        else
        {
            MessageBox.Show("TextBox is empty!");
        }
    }

這是國家/地區表格的外觀(CountryID,Town,TownDate):

在此處輸入圖片說明

它總是說記錄被刪除,即使沒有刪除。

對於UPDATE,INSERT和DELETE語句,ExecuteNonQuery的返回值是受命令影響的行數。

因此,將代碼修改為:

  var n= komDelete.ExecuteNonQuery();
  if (n >0 )
   {
            MessageBox.Show("Deleted");
   }

編輯

查詢中的問題是:

  • 參數數據類型s1,s2是字符串,它們應作為整數傳遞。
  • 使用*,並且應為%(訪問使用%,請參閱我的評論)

因此,您必須將代碼修改為:

        var p1 = sTown + "%"; // not *
        komDelete.Parameters.AddWithValue("@p1", p1);
        var p2 = int.Parse(s1); //convert to numeric data type
        var p3 = int.Parse(s2);
        komDelete.Parameters.AddWithValue("@p2", p2);
        komDelete.Parameters.AddWithValue("@p3", p3);


      var n= komDelete.ExecuteNonQuery();
     if (n >0 )
     {
            MessageBox.Show("Deleted");
     }

我使用Access 2007和2007 Office system驅動程序:數據連接組件對該代碼進行了測試,它工作正常,並刪除了該行。

嘗試這個:

        if (textBox1.Text != "")
    {
        //retrieve data
        string sTown, sMonth, sYear;
        sTown = textBox1.Text.Substring(0, 3);
        sMonth = textBox1.Text.Substring(3, 2);
        sYear = textBox1.Text.Substring(5);

        //validate input
        bool valid_town = new Regex(@"[a-z]", RegexOptions.IgnoreCase).IsMatch(sTown) && new Regex(@"[^0-9]").IsMatch(sTown) && sTown.Length ==3;
        bool valid_month = new Regex(@"[0][1-9]|[1][0-2]").IsMatch(sMonth) && new Regex(@"[^a-z]", RegexOptions.IgnoreCase).IsMatch(sMonth) && sMonth.Length ==2;

        int year = 0;
        bool isNum = int.TryParse(sYear,out year);
        bool valid_year = new Regex(@"[^a-z]", RegexOptions.IgnoreCase).IsMatch(sYear) && sYear.Length == 4 && (isNum ? year > 1980 && year < 2100 : false);



        string newLine = System.Environment.NewLine;

        //if input valid
        if (valid_town && valid_month && valid_year)
        {
            //create sql statements
            string sWhere = String.Format("WHERE Town LIKE {0} and month(TownDate) = {1] and year(TownDate) = {2}", sTown,sMonth,sYear);
            string sCount = String.Format("SELECT COUNT(*) FROM Country {0}", sWhere);
            string sDelete = String.Format("DELETE * FROM Country {0}",sWhere);

            //counts; to be deleted, actually deleted
            int initialCount = 0;
            int deletedCount = 0;

            try
            {
                //create connection//NOTE: Using 'Use' statement will handle opening and closing. I dont know where you created your initial 'connection' object but it could cause you problems by haven a connection that is being used in multiple methods.
                using (OleDbCommand connection = new OleDbCommand(ConnectionString))
                {
                    //get total rows to be affected
                    connection.CommandText = sCount;
                    initialCount = connection.ExecuteNonQuery();

                    //delete rows and get delete count
                    connection.CommandText = sDelete;
                    deletedCount = connection.ExecuteNonQuery();
                    //display message
                    MessageBox.Show(String.Format("Found {0} rows to delete. {1}Deleted {2} rows.", initialCount, newLine, deletedCount));

                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
            finally
            {
                connection.Close();
            }
        }
        {
            //else; input not valid
            MessageBox.Show(String.Format("Failed validation of TextBox:{0}Country:{1}{2}Month{3}{4}Year{5}.", newLine, valid_town.ToString(), newLine, valid_month.ToString(), newLine, valid_year.ToString())); ;

        }
    }
    else
    {
        MessageBox.Show("TextBox is empty!");
    }

您將需要使用以下方法添加它:

using System.Text.RegularExpressions;

我沒有機會創建示例項目自己嘗試...

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM