Error; The connection has not been closed. The current state of the connection is opened SqlServer 2016

4

I'm creating an application in Visual Studio in C #, and connecting to sqlserver on Server Explore was all correct in connection testing.

This is my connection string:

return "Data Source=DESKTOP-58ASAQP\MSSQLSERVER16;Initial Catalog=ControleDeEstoque;User ID=sa;Password=root";

However, when entering a data in the form I get the following message:

  

"The connection has not been closed. The current state of the connection opens."

Has anyone ever had this error? Does this require any configuration in Sqlserver?

    
asked by anonymous 17.04.2016 / 23:06

1 answer

1

This is simply because you are trying to open a connection to the bank when it is already open.

See the example below.

using System;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Text;

namespace stackoverflow
{
    public partial class ConexaoAberta : System.Web.UI.Page
    {
        protected String ConnString
        {
            get
            {
                return ConfigurationManager.ConnectionStrings["DBConn"].ToString();
            }
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            SqlConnection conn = new SqlConnection();
            conn.ConnectionString = ConnString;

            SqlDataAdapter adapter = new SqlDataAdapter();
            DataTable dt = new DataTable();
            StringBuilder query = new StringBuilder();
            query.Append("SELECT *  FROM [stackoverflow].[dbo].[Categoria]");

            conn.Open();
            adapter.SelectCommand = new SqlCommand(query.ToString(), conn);
            adapter.Fill(dt);
            GetSubCategoria(conn);
        }

        public void GetSubCategoria(SqlConnection conn)
        {
            SqlDataAdapter adapter = new SqlDataAdapter();
            DataTable dt = new DataTable();
            StringBuilder query = new StringBuilder();
            query.Append("SELECT * FROM [stackoverflow].[dbo].[SubCategoria]");

            conn.Open(); // Aqui você tenta abri novamente a conexão, sendo que o método acima não tinha
            // fechado ela.
            adapter.SelectCommand = new SqlCommand(query.ToString(), conn);
            adapter.Fill(dt);
        }
    }
}

In the last method public void GetSubCategoria(SqlConnection conn) , I can my connection and having it open again conn.Open(); , with the current status being open generating the error.

Certainlyyourerrorisbeinggeneratedwhenyouattempttoenteryourdata.

Makesuretheconnectionstatusisopen,themostadvisablewouldbetowrapallyourconnectionsinblocks.

using .

using (var conn = new SqlConnection(_dbconnstr)) 
{
    //code
}

Or try finally .

SqlConnection conn = new SqlConnection(_dbconnstr);
try
{
    //code
}
finally
{
    conn.Dispose();
}
    
24.08.2016 / 21:44