简体   繁体   English

C# - Dapper/MySql - 如何使用用户定义的变量运行查询

[英]C# - Dapper/MySql - How to run a query with user-defined variable

I've been trying to run this code:我一直在尝试运行这段代码:

using System;
using Dapper;
using MySql.Data.MySqlClient;

namespace DapperTests
{
    class Program
    {
        static void Main(string[] args)
        {
            using (var db = new MySqlConnection(@"mysql_connstr_here"))
            {
                var sql = @"
                    set @foo := (select count(*) from table1);
                    select table2.*, @foo from table2;";
                var result = db.Query(sql);
            }
            Console.ReadLine();
        }
    }
}

But I get the following exception:但我得到以下异常:

System.NullReferenceException: 'Object reference not set to an instance of an object.'
This exception was originally thrown at this call stack:
  MySql.Data.MySqlClient.MySqlConnection.Reader.set(MySql.Data.MySqlClient.MySqlDataReader)

My first guess is that the variable is being treated as a SqlParameter, and since I'm not passing any argument to it, my code fails.我的第一个猜测是该变量被视为 SqlParameter,并且由于我没有向它传递任何参数,所以我的代码失败了。 Is there a way to run a query like that using Dapper?有没有办法使用 Dapper 运行这样的查询?

I've found this in the Dapper documentation :我在Dapper 文档中找到了这个:

In order to use Non-parameter SQL variables with MySql Connector, you have to add the following option to your connection string:为了将非参数 SQL 变量与 MySql 连接器一起使用,您必须将以下选项添加到连接字符串中:

Allow User Variables=True允许用户变量=True

Make sure you don't provide Dapper with a property to map.确保您没有向 Dapper 提供 map 的属性。

So all I needed to do was to Allow User Variables=True to the connection string.所以我需要做的就是Allow User Variables=True到连接字符串。 It worked.有效。

The NullReferenceException you are receiving is likely because you have not defined foo as a parameter.您收到的 NullReferenceException 可能是因为您没有将 foo 定义为参数。

  using (var db = new MySqlConnection(@"mysql_connstr_here"))
  {
    var sql = dbConnection.QueryFirstOrDefault<int>(
      @" 
      select @foo;",
      new
      {
        foo = userAssignedVariable
      });
  }

Or you can else write your sql with a valid sql variable declaration:或者您可以使用有效的 sql 变量声明编写 sql:

var sql = @"declare @foo int = 0; select @foo;";

Note: tested with Sql Server, not MySql. I don't use it.注意:使用 Sql 服务器测试,而不是 MySql。我不使用它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM