c# – MySQL ODBC存储过程结果缺少列

我有一组存储过程,我用来填充ASP.Net CheckBoxList.从代码运行此过程为{CALL ProcedureName(params);使用类型设置为存储过程,我似乎只得到一个部分结果(即实际结果中的许多列都丢失了.)

如果我从查询中复制CommandText(使用断点来获取发送的确切文本)并直接在Navicat(或任何其他MySQL GUI)中运行它,我会获得所有预期的列.

这是不起作用的代码:

using (OdbcCommand command = OdbcConnection.CreateCommand())
{
    command.CommandType = CommandType.StoredProcedure;
    command.CommandText = "{ " + string.Format(StoredProcedureCall, foundationId, fpids, "", "", "NULL", "2001/01/02", "2001/01/01", "*") +
                          " }";
    using (OdbcDataReader reader = command.ExecuteReader())
    {

        for (int i = 0; i < reader.FieldCount; i++)
        {
            columns.Add(reader.GetName(i));
        }
    }
}

如果我将代码更改为以下代码,则它开始工作(仅添加另一个使用):

using (OdbcConnection)
using (OdbcCommand command = OdbcConnection.CreateCommand())
{
    command.CommandType = CommandType.StoredProcedure;
    command.CommandText = "{ " + string.Format(StoredProcedureCall, foundationId, fpids, "", "", "NULL", "2001/01/02", "2001/01/01", "*") +
                          " }";
    using (OdbcDataReader reader = command.ExecuteReader())
    {

        for (int i = 0; i < reader.FieldCount; i++)
        {
            columns.Add(reader.GetName(i));
        }
    }
}

这里发生了什么?

这里是参考OdbcConnection属性:

public static OdbcConnection OdbcConnection
{
    get
    {
        // If we have no connection or our connection isn't open
        if (null == odbcConnection || ConnectionState.Open != odbcConnection.State)
        {
            odbcConnection = new OdbcConnection(BaseAccess.DBConnectionString);
            odbcConnection.Open();
        }

        return odbcConnection;
    }
}

最佳答案 这可能是Odbc MySql驱动程序中的错误.尝试使用
ADO.NET driver.此外,我建议您不要在静态属性中手动处理连接.将此任务保留给ADO.NET,它将有效地处理连接池:

using (var conn = new MySqlConnection(DBConnectionString))
using (var cmd = conn.CreateCommand())
{
    conn.Open();
    cmd.CommandType = CommandType.StoredProcedure;
    cmd.CommandText = "sp_name";

    cmd.Parameters.Add(new SqlParameter("@foundationId", foundationId));
    cmd.Parameters.Add(new SqlParameter("@fpids", fpids));
    ...

    using (var reader = cmd.ExecuteReader())
    {
        for (int i = 0; i < reader.FieldCount; i++)
        {
            columns.Add(reader.GetName(i));
        }
    }
}
点赞