Domanda

Hi I am trying to get data from a database shown in a textbox. Doing this I have created three classes: Dal, Controller and TestForm. The thing is that I dont really know where to open the connection nor where to close it. This is what I've done.

In the class Dal I have:

  using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    using System.Data.SqlClient;
    using System.Data.Odbc;

    namespace TestingDatabaseConnection
    {
        class Dal
        {
    private SqlConnection connection = new SqlConnection();

        public SqlConnection GetConnection()
        {

            if (connection == null)
            {
               connection.ConnectionString = "Server=Mnemonics-DAT;Database=mem;    Integrated Security = true;";
            }

            return connection;
        }

     public SqlDataReader GetData() 
        {
            SqlDataReader sqlReads = null;

                SqlCommand sqlCommand = new SqlCommand("select * from table_name", GetConnection());
                 sqlReads = sqlCommand.ExecuteReader();

            return sqlReads;


        }
    }
    }

In the class Controller I have:

 using System;
    using System.Collections.Generic;
    using System.Data.SqlClient;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;

    namespace TestingDatabaseConnection
    {
    class Controller
    {
        private Dal dal = new Dal();

        public SqlDataReader GetData()
        {
            return dal.GetData();
        }
    }
    }

and finally in the form:

public partial class TestForm : Form
{
Controller controll; 

public TestForm()
{
    InitializeComponent();
    controll = new Controller();
}

private void showBtn_Click(object sender, EventArgs e)
{
    try
    {
        SqlDataReader sqlReader = controll.GetData();
        while (sqlReader.Read())
        {
            infTxtBox.Text = sqlReader.ToString();
        }
    }
    catch (Exception e1)
    {
        MessageBox.Show("Something is wrong: " + e1);
    }

}

}

The message I get says "Something is wrong: ExecuteReader requires an open and available Connection. The connection's current state is closed.


What I have tried to do to solve the problem(in the class Dal):

Making a property that gets the connection value like this:

public SqlConnection Connect
    {
        get
        {
            return connection;
        }
    }

And then using it in the method GetData():

 public SqlDataReader GetData() 
        {
            SqlDataReader sqlReads = null;
            try
            {
                 //I call the method Open() here
                Connect.Open();
                SqlCommand sqlCommand = new SqlCommand("select * from table_name", GetConnection());
                sqlReads = sqlCommand.ExecuteReader();
            }
            catch (Exception e)
            {
                Console.WriteLine("Error is: " + e);
            }
            finally
            {
                //and close it here
                Connect.Close();
            }
            return sqlReads;


        }

The error message I get now says: "Something is wrong: Invalid attempt to call Read when reader is closed" While referring to the class TestForm.

È stato utile?

Soluzione

Problem is here:

if (connection == null)
{
     connection.ConnectionString = "Server=Mnemonics-DAT;Database=mem;    Integrated Security = true;";
}

Your connection can't be null because you initializing it before calling GetConnection method.Instead check your connection string:

if(connection.ConnectionString == "")
{
    connection.ConnectionString = "Server=Mnemonics-DAT;Database=mem;    Integrated Security = true;";
}

Probably it would better if you use using statements,it will automatically Dispose your Connection object when it's job is done, just define a connection string variable then use:

string connString = "Server=Mnemonics-DAT;Database=mem; Integrated Security = true";

using(var conn = new SqlConnection(connString))
using(var sqlCommand = new SqlCommand("select * from table_name", conn))
{
      conn.Open();
      sqlReads = sqlCommand.ExecuteReader();
      conn.Close();
}

Altri suggerimenti

Problem : in Dal class file you are not opening your connection object connection before reading the data.

Solution : You need to Open the SqlConnection object using Open() method before reading the data.

Try This:

    public SqlDataReader GetData() 
    {
        SqlDataReader sqlReads = null;
        SqlCommand sqlCommand = new SqlCommand("select * from table_name", GetConnection());
        connection.Open(); //Open your connection object here.
        sqlReads = sqlCommand.ExecuteReader();
        return sqlReads;
    }

Its because you're trying to read your SqlDataReader on a closed connection.

Do not call connection.close() in your getData() method instead add a method to your Dal class like so :

public void CloseConnection()
{
    connect.close()
}

and then call your closeConnection method after looping trough your DataReader :

SqlDataReader sqlReader = controll.GetData();
        while (sqlReader.Read())
        {
            infTxtBox.Text = sqlReader.ToString();
        }

control.CloseConnection();
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top