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

Fang

我正在使用.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从一个命令复制到另一个命令,或者也复制参数。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章