簡體   English   中英

參數化的 MySQL 查詢不返回任何結果

[英]Parameterized MySQL query doesn't return any results

我正在使用 .NET Connector 6.8.6 從 C# 查詢 MySQL 數據庫

我編寫了以下查詢函數:

public DataSet ExecuteQuery()
    {
        try
        {
            this.dataset = new DataSet();
            dataset.Clear();

            conn = new MySqlConnection(this.queryConfig.GetConString());
            conn.Open();

            MySqlCommand cmd = new MySqlCommand(this.queryText, conn);

            MySqlDataAdapter _mySQLAdapter = new MySqlDataAdapter(cmd);

            _mySQLAdapter.Fill(dataset);
            conn.Close();

            return this.dataset;
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
            return this.dataset;
        }
        finally
        {
            if (conn != null) conn.Close();
        }

    }

現在我正在努力保護我的查詢免受 SQL 注入的影響。

這是我的查詢功能:

string queryText2 = string.Format("SELECT TABLE_NAME AS 'table_name', "
                             + "round(((data_length + index_length) / 1024 / 1024), 2) AS 'Size(MB)'"
                             + "FROM information_schema.TABLES "
                             + "WHERE table_schema = @dbname");


            MySqlCommand command = new MySqlCommand(queryText2);
            command.Parameters.AddWithValue("@dbname", Convert.ToString(databaseName));

但是,這似乎不起作用。 查詢字符串中的@dbname 永遠不會被 .Parameters.AddWithValue 替換,因此查詢失敗。

有什么方法可以讓我在不廢棄我完整的 Query 類的情況下工作嗎?

問題在這里:

public DataSet ExecuteQuery()
{
    ...
        MySqlCommand cmd = new MySqlCommand(this.queryText, conn);
        // parameters are lost!!
        MySqlDataAdapter _mySQLAdapter = new MySqlDataAdapter(cmd);

     ...
}

您通過復制命令文本創建了一個新的MySqlCommand ,但沒有復制參數 因此,您添加的參數會丟失。 我建議檢查您的設計,以停止將 sql 從一個命令復制到另一個命令,或者也復制參數。

為什么不喜歡這個?

string queryText2 = string.Format("SELECT TABLE_NAME AS 'table_name', "
                                 + "round(((data_length + index_length) / 1024 / 1024), 2) AS 'Size(MB)'"
                                 + "FROM information_schema.TABLES "
                                 + "WHERE table_schema = {0}",Convert.ToString(databaseName));

暫無
暫無

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

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