参数化MySQL查询不会返回任何结果

时间:2015-10-27 12:21:59

标签: c# mysql .net

我正在使用.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类的情况下使用它?

2 个答案:

答案 0 :(得分:1)

问题在于:

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

     ...
}

您正在通过复制命令文本创建 MySqlCommand,但复制参数。因此,您添加的参数会丢失。我建议检查你的设计,要么停止将sql从一个命令复制到另一个命令,要么也复制参数。

答案 1 :(得分:-2)

为什么不喜欢这个?

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));
相关问题