【问题标题】:Where am I supposed to call the method connection.Open() using C#?我应该在哪里使用 C# 调用方法 connection.Open()?
【发布时间】:2014-02-09 19:02:46
【问题描述】:

您好,我正在尝试从文本框中显示的数据库中获取数据。为此,我创建了三个类: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 时。

【问题讨论】:

    标签: c# database datareader


    【解决方案1】:

    问题就在这里:

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

    您的连接不能为空,因为您在调用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();
    }
    

    【讨论】:

    • 嗨 Selman22,感谢您的帮助,但我收到了同样的错误消息。更新到 connection.ConnectionString == "" 但它不起作用。
    • @Mnemonics 应该是 connection.ConnectionString == "" 而不是 connection.ConnectionString == null 我改了
    【解决方案2】:

    问题: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;
        }
    

    【讨论】:

    • 哦,我以为我已经尝试过了,但我错了。谢谢你的正确答案。我会接受的。
    • @Mnemonics:不客气 :) 很高兴能帮助到你。
    • @SudhakarTillapudi 实际上他正在调用 Open 方法,但他没有设置连接字符串,因为 if 语句总是变成 false(在GetConnection 方法内部)
    • @Selman22: 是的,亲爱的,我只是注意到最后但在第一个 DAL 课程中它没有打开,这很重要,谢谢亲爱的你的宝贵意见。
    • 我想对我的帖子进行一些批评。这个问题有效还是我应该更具体?是代码太多还是“足够”让您通过它并找到解决方案?下次我问问题时应该怎么想?
    【解决方案3】:

    这是因为您试图在关闭的连接上读取您的 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();
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-01-06
      • 2018-10-04
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多