首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> .NET 網頁程式設計 >> ASP.NET 基礎 >> ASP.NET 基礎

SQL Server 批量資料替換工具 V1.0 開發實錄:從 sp_helpdb 到正則替換完整流程

     編輯:ASP.NET 基礎

面對 SQL 注入或髒資料大量汙染資料庫時,逐筆修改極不實際。本文記錄開發一款 WinForms 批量資料替換小工具的完整思路:從列舉資料庫、資料表、欄位,到支援正則運算式的查找替換,附關鍵程式碼與介面截圖。

開發架構三步驟

步驟一:測試連線並列舉所有資料庫

使用系統預存程序 sp_helpdb 取得資料庫清單:

private void btnTest_Click(object sender, EventArgs e)
{
    btnTest.Enabled = false;
    saveConfig();

    ConfigInfo.Server = txtIP.Text.Trim();
    ConfigInfo.DataBase = "master";
    ConfigInfo.UID = txtUID.Text.Trim();
    ConfigInfo.Pwd = txtPwd.Text.Trim();

    try
    {
        DataTable dt = Data.SqlHelper.ExecuteDataset(ConfigInfo.getConnect(), CommandType.Text, "sp_helpdb").Tables[0];
        cmbDataBaseList.DataSource = dt;
        cmbDataBaseList.DisplayMember = "name";
        cmbDataBaseList.SelectedIndex = 0;
        cmbDataBaseList.DropDownStyle = ComboBoxStyle.DropDownList;
        ExecuteFilterBtn.Enabled = true;
    }
    catch (Exception ex)
    {
        ExecuteFilterBtn.Enabled = false;
        MessageBox.Show("錯誤:" + ex.Message);
    }
    finally { btnTest.Enabled = true; }
}

步驟二:選擇資料庫後列舉所有使用者資料表

查詢 sysobjects 系統表取得 xtype='U' (使用者資料表):

private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
    chkboxTableList.Items.Clear();
    ConfigInfo.DataBase = ((DataRowView)cmbDataBaseList.SelectedItem)["name"].ToString();
    DataSet ds = Data.SqlHelper.ExecuteDataset(ConfigInfo.getConnect(), CommandType.Text, 
        "SELECT [name] FROM sysobjects WHERE xtype='U' ORDER BY [name] ASC");
    foreach (DataRow row in ds.Tables[0].Rows)
        chkboxTableList.Items.Add(row["name"].ToString());
}

步驟三:執行批量替換核心邏輯

遍歷勾選的資料表,逐行逐欄位檢查並替換,支援純文字與正則兩種模式:

private void ExecuteFilterBtn_Click(object sender, EventArgs e)
{
    saveConfig();
    total = 0;
    if (chkboxTableList.CheckedIndices.Count == 0) return;

    // 確認空查找字串
    if (txtSearchKey.Text.Trim() == "")
    {
        if (MessageBox.Show("查找內容為空,確認執行?", "提示", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No)
            return;
    }

    ExecuteFilterBtn.Enabled = false;
    string searchStr = txtSearchKey.Text.Trim() == "" ? " " : txtSearchKey.Text;
    string replaceStr = txtReplaceStr.Text;
    KeyType kt = chkIsRegex.Checked ? KeyType.Regex : KeyType.Text;

    // 收集目標資料表資訊
    List<TableInfo> tabList = new List<TableInfo>();
    foreach (int idx in chkboxTableList.CheckedIndices)
    {
        string tabName = chkboxTableList.Items[idx].ToString();
        TableInfo tInfo = FilterInfo.initTableInfo(tabName);
        if (tInfo != null) tabList.Add(tInfo);
    }

    try
    {
        if (tabList.Count == 0) return;
        pBar1.Visible = true; pBar1.Minimum = 1; pBar1.Maximum = tabList.Count; pBar1.Value = 1; pBar1.Step = 1;

        foreach (TableInfo info in tabList)
        {
            FilterInfo.Execute(info, searchStr, replaceStr, kt); // 核心替換邏輯封裝於 FilterInfo
            pBar1.PerformStep();
        }
    }
    catch (Exception ex) { MessageBox.Show("異常:" + ex.Message); }
    finally { ExecuteFilterBtn.Enabled = true; }

    MessageBox.Show("資料替換完畢,共修改 " + total + " 筆資料!");
}

介面操作流程

  1. 輸入 SQL Server IP、帳號、密碼,點擊「測試連線」載入資料庫下拉選單
  2. 選擇目標資料庫,下方自動列出所有使用者資料表(核取方塊列表)
  3. 勾選需處理的資料表(可多選)
  4. 輸入「查找內容」與「取代內容」,可勾選「正則比對」啟用 Regex
  5. 點擊「執行替換」,進度條顯示處理進度,完成後彈出統計訊息

關鍵技術細節

  • FilterInfo.Execute:核心替換方法,內部針對各資料表動態建構 UPDATE SQL,針對字串型欄位 (varchar, nvarchar, text 等) 執行替換
  • 正則支援:透過 KeyType.Regex 區分模式,底層使用 Regex.Replace
  • 進度回報:以資料表為單位更新 ProgressBar,避免長時間無回應
  • 設定持久化:saveConfig() 記住連線資訊,下次啟動自動填入

實際修復案例截圖

工具主介面 被注入的惡意資料 編寫查找與取代內容 資料恢復原貌

總結與下載

此工具專為緊急資料清洗設計,介面簡單直觀,核心邏輯封裝於 FilterInfo 類別。完整原始碼可至文章底部下載連結取得。使用前請務必備份資料庫,建議先於測試環境驗證替換邏輯。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved