SelectCommand.Connection属性尚未初始化。 MySQL的

问题描述 投票:0回答:1

事实证明我正在使用SignalR,在html视图中我向客户端发出以下请求:

 var myHub = $.connection.myHub;
    var direccionWeb = $("#direccionWeb").val().toString();
    $.connection.hub.url = direccionWeb + "/signalr";
    $.connection.hub.start().done(function () {
        myHub.server.broadcastMessageToPrinterReportTicket(global_venta, global_mesa, nombregarzon, idgrupo, grupo);

    }).fail(function (error) {
        console.error(error);
    });

在Hub文件中,我有以下内容:

public void BroadcastMessageToPrinterReportTicket(String global_venta,String global_mesa,String nombregarzon,String idgrupo, String grupo)
{
    string namePrinter = group;
    DataTable dt = new DataTable();

    string sql = "SELECT " +
        "cant," +
        "det " +
        "FROM producto " +                
        "WHERE venta=@global_venta AND venta>0 AND menu.grupo=@idgrupo AND comandasd.pedido=0";
    conexion.conectar(); 

    using (MySqlCommand command = new MySqlCommand(sql, conexion.con))
    {
        command.Parameters.AddWithValue("@global_venta", global_venta);
        command.Parameters.AddWithValue("@idgrupo", idgrupo);
        using (MySqlDataAdapter reader = new MySqlDataAdapter(command))
        {
            using (MySqlDataAdapter sda = new MySqlDataAdapter(command))
            {
                sda.Fill(dt);
            }
        }
    }
    conexion.cerrar();


    Clients.All.printReport(datos, ........);
}

包含连接类的文件如下:

public void conectar()
{
    try
    {
        string ip = HttpContext.Current.Session["ip"].ToString();
        string db = HttpContext.Current.Session["db"].ToString();
        string user = HttpContext.Current.Session["user"].ToString();
        string pass = HttpContext.Current.Session["pass"].ToString();

        con = new MySqlConnection("server=" + ip + ";user id=" + user + ";password=" + pass + ";database=" + db + ";port=3306;Allow User Variables=true"); 
        con.Open();
    }
    catch
    {

    }
}

但是当我尝试向DataTable添加数据时,也就是说,在sda.Fill(dt)所说的行上,出现以下错误:SelectCommand.Connection属性尚未初始化。

奇怪的是,当我使用它时,控制器中声明的功能相同,它可以正常工作。我想要的是能够获得具有BroadcastMessageToPrinterReportTicket接收的参数的数据表并将其发送到客户端。

如果有人知道如何纠正错误或一些帮助,我们将不胜感激。

问候

c# mysql sql asp.net-mvc signalr-hub
1个回答
2
投票

SelectCommand.Connection属性尚未初始化

在使用命令之前,需要设置MySqlCommand.Connection属性。例外是告诉你它尚未设置。

您正在使用设置它的构造函数:

using (MySqlCommand command = new MySqlCommand(sql, conexion.con))

逻辑推理是conexion.con == null

我们看到con设置在conectar。但是,该代码周围有一个try / catch块。因此,必须在分配con之前抛出(并忽略)异常。

最可能的解释是,HttpContext.Current.Session["..."]值中的一个(或多个)是null,所以在它上面调用.ToString()会抛出一个NullReferenceException

建议:

  1. 不要抓住并忽略异常;它们通常表明需要正确处理的真正问题。
  2. 会话状态似乎是存储数据库凭据的一个非常奇怪的地方;请考虑使用web.config设置。 (或者您可能希望首先对其进行硬编码,看看是否可以使其余代码正常工作,然后在您知道其他所有内容正确后将其移至Settings。)
© www.soinside.com 2019 - 2024. All rights reserved.