在使用网站一段时间后,加载内容等。此消息显示“填充:SelectCommand.Connection属性尚未初始化”!
我认为这是因为sql连接,但是不确定...我想知道我能做些什么来防止这种情况发生,每次发生这种情况时,我都必须上载一个文件(SQL类,可以建立连接),然后网站再次开始工作。

我的SQL连接:

public class SQL
{

    SqlCommand comandos;
    public SqlConnection sql()
    {
        string Server = @"server";
        string Username = "user";
        string Password = "pass";
        string Database = "database";
        string ConnectionString = "Data Source=" + Server + ";";
        ConnectionString += "User ID=" + Username + ";";
        ConnectionString += "Password=" + Password + ";";
        ConnectionString += "Initial Catalog=" + Database;

        SqlConnection Connection = new SqlConnection();
        try
        {
            Connection.ConnectionString = ConnectionString;
            Connection.Open();
            return Connection;
        }
        catch (Exception)
        {
            if (Connection != null)
            {
                Connection.Dispose();
        }
        return null;
        }
    }

    public void FazerComando(string comando)
    {
        comandos = new SqlCommand(comando, sql());
        comandos.ExecuteNonQuery();
    }

    public DataTable Execute(string comando)
    {
        SqlDataAdapter SQLDataAdapter = new SqlDataAdapter(comando, sql());
        DataTable dtResult = new DataTable();
        SQLDataAdapter.Fill(dtResult);
        return dtResult;
    }
}

最佳答案

这可能与您的问题有关,但是在任何情况下,都应该解决此问题:完成连接后,您无需处理连接。您应该使用using

    public void FazerComando(string comando)
    {
        using (var conn = sql())
        {
            comandos = new SqlCommand(comando, conn);
            comandos.ExecuteNonQuery();
        }
    }
    public DataTable Execute(string comando)
    {
        using (var conn = sql())
        {
            SqlDataAdapter SQLDataAdapter = new SqlDataAdapter(comando, conn);
            DataTable dtResult = new DataTable();
            SQLDataAdapter.Fill(dtResult);
            return dtResult;
        }
    }

关于c# - 填充:SelectCommand.Connection属性尚未初始化,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/11072021/

10-10 18:55