簡體   English   中英

我應該在哪里使用C#調用方法connection.Open()?

[英]Where am I supposed to call the method connection.Open() using C#?

嗨,我試圖從文本框中顯示的數據庫中獲取數據。 這樣做我創建了三個類:Dal,Controller和TestForm。 問題是,我真的不知道在哪里打開連接,也不知道在哪里關閉它。 這就是我所做的。

在Dal級我有:

  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;


        }
    }
    }

在類控制器中我有:

 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();
        }
    }
    }

最后是以下形式:

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);
    }

}

}

我收到的消息說“出錯了:ExecuteReader需要一個開放且可用的連接。連接的當前狀態已關閉。


我試圖解決這個問題(在Dal類):

創建一個獲取連接值的屬性,如下所示:

public SqlConnection Connect
    {
        get
        {
            return connection;
        }
    }

然后在方法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;


        }

我現在得到的錯誤信息是:“出現問題:讀取器關閉時調用Read的無效嘗試”同時引用了TestForm類。

問題在這里:

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

您的連接不能為null,因為您在調用GetConnection方法之前初始化它。相反檢查您的連接字符串:

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

如果你使用using statements可能會更好,它會在你的工作完成時自動Dispose你的Connection對象,只需定義一個連接字符串變量然后使用:

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();
}

問題:Dal類文件中,您沒有在讀取數據之前打開連接對象connection

解決方案:您需要在讀取數據之前使用Open()方法打開SqlConnection對象。

嘗試這個:

    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;
    }

這是因為你試圖在一個封閉的連接上讀取你的SqlDataReader。

不要在你的getData()方法中調用connection.close()而是向Dal類添加一個方法,如下所示:

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

然后通過DataReader循環后調用closeConnection方法:

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

control.CloseConnection();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM