C# 我可以打开SqlConnection一次,但我可以';不要再这样做了

C# 我可以打开SqlConnection一次,但我可以';不要再这样做了,c#,sqlconnection,C#,Sqlconnection,我的程序运行,并且它最初成功地连接到数据库。我可以运行查询,一切正常。但是,我似乎无法断开连接并重新连接到数据库。输出显示:“System.Data.dll中发生了'System.InvalidOperationException'类型的第一次意外异常”以下是我的连接方法: using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Dra

我的程序运行,并且它最初成功地连接到数据库。我可以运行查询,一切正常。但是,我似乎无法断开连接并重新连接到数据库。输出显示:“System.Data.dll中发生了'System.InvalidOperationException'类型的第一次意外异常”以下是我的连接方法:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Threading;
using System.Data.SqlClient;

namespace WindowsFormsApplication1
{
    class TCNInteraction
    {
        static string connectionString = "Server=localhost\\SQLEXPRESS;Database=TCN;Trusted_Connection=true";
        Button theButton;
        TextBox theTextBox;
        bool currentlyConnectedToADatabase = false;
        SqlConnection cnn = new SqlConnection(connectionString);
        /*
         *Uses the already existing SQL connection string and attempts to establish a connection 
         */
        public bool connectToDatabase(Button inputButton, TextBox inputDatabaseBox)
        {
            theButton = inputButton;
            try
            {
                Console.WriteLine("Attempting to open connection...");
                if (cnn.State != ConnectionState.Open)
                {
                    Console.WriteLine("About to open the connection");
                    cnn.Open();
                }
                Console.Write("I opened the connection!");
                currentlyConnectedToADatabase = true;
                displayRowsOfDatabase(inputDatabaseBox);
                theButton.Text = "Connected";
                return true;

            }
            catch (Exception ex)
            {
                MessageBox.Show("Cannot open connection!");
                return false;
            }
            finally
            {
                cnn.Close();
            }

        }

        private void displayRowsOfDatabase(TextBox inputDatabaseBox)
        {

            theTextBox = inputDatabaseBox;
            using (cnn)
            {

                SqlCommand command = new SqlCommand("SELECT SomeNumber,SomeText, AnotherNumber FROM tcn.Demo;", cnn);
                SqlDataReader reader = command.ExecuteReader();


                if (reader.HasRows)
                {
                    while (reader.Read())
                    {
                        string printString = int.Parse(reader["SomeNumber"].ToString()) + " " + reader["SomeText"].ToString() + " " + int.Parse(reader["AnotherNumber"].ToString()) + Environment.NewLine;
                        theTextBox.Text += printString;
                    }
                }
                else
                {
                    Console.WriteLine("No rows found.");
                }
                reader.Close();
            }
            cnn.Close();
        }


        public void disconnectFromDatabase()
        {
            MessageBox.Show("Disconnected from Database");
            cnn.Close();
            theButton.Text = "Connect to Database";
            //theTextBox.Text = "";
            currentlyConnectedToADatabase = false;
        }
    }
}

我想你希望你的if声明

        //THIS IS WHERE I GET STUCK THE SECOND TIME
        if (cnn.State == ConnectionState.Open)
        {
            cnn.Close();
            cnn.Open();
        }

用这个!=只有当连接未打开时,您才调用cnn.Close()。

您的
try/catch
块没有关闭您的连接。负责最后关闭与
块的连接。即使程序中发生任何异常,它也会关闭连接。尝试如下

public bool connectToDatabase(Button inputButton, TextBox inputDatabaseBox)
{
    theButton = inputButton;
    try
    {
            Console.WriteLine("Attempting to open connection...");

            //THIS IS WHERE I GET STUCK THE SECOND TIME
            if (cnn.State != ConnectionState.Open)
            {
                cnn.Open();
            }
            Console.Write("I opened the connection!");
            currentlyConnectedToADatabase = true;
            displayRowsOfDatabase(inputDatabaseBox);
            theButton.Text = "Connected";
            return true;

    }
    catch (Exception ex)
    {
        MessageBox.Show("Cannot open connection!");
    }
    finally
    {
        cnn.Close();
    }

}
public void disconnectFromDatabase()
    {
        MessageBox.Show("Disconnected from Database");
        if(cnn.State == ConnectionState.Open)
        {
            cnn.Close();
        }
        theButton.Text = "Connect to Database";
        //theTextBox.Text = "";
        currentlyConnectedToADatabase = false;
    }

try/catch
中包含
finally
块以关闭连接。另外,我建议使用
bool
变量来确定连接是否成功

public bool connectToDatabase(Button inputButton, TextBox inputDatabaseBox)
{
    bool status = false;

    theButton = inputButton;
    try
    {
        Console.WriteLine("Attempting to open connection...");

        //THIS IS WHERE I GET STUCK THE SECOND TIME
        if (cnn.State != ConnectionState.Open)
        {
            cnn.Open();
        }

        Console.Write("I opened the connection!");
        currentlyConnectedToADatabase = true;
        displayRowsOfDatabase(inputDatabaseBox);
        theButton.Text = "Connected";

        status = true;
    }
    catch (Exception ex)
    {
        MessageBox.Show("Cannot open connection!");
    }
    finally
    {
        cnn.Close();
    }

    return status;
}

您似乎试图关闭正在引发异常的已关闭连接:

if (cnn.State == ConnectionState.Open)
{
   cnn.Close();
}
cnn.Open();

如果连接已打开,请尝试以上方法关闭连接,然后打开连接

连接从未关闭。包括一个关闭连接的
finally
块。这将确保即使执行
catch
块,它也会关闭。另外,我将包括变量
bool successful=false
,并在
try
块中设置它
true
,在
catch
中设置它
false
,并返回
successful
而不是true。您的方法将始终返回现在的
true
。尝试了您的代码后,仍然会出现相同的错误,有什么想法吗?我已经添加了代码的其余部分,因为这可能是问题所在。它实际上只是从connectToDatabase()中的catch块抛出异常。但是,如果我注释掉displayRowsOfDatabase(inputDatabaseBox),它似乎成功连接。我认为displayRowsOfDatabase()中有东西试图打开已经打开的东西。我似乎无法将手指放在上面。我会通过
displaysowsofdatabase()
找到问题发生的确切位置。在开口支架处放置断点,然后按F11键(默认)逐行移动。您还可以在代码周围放置一个
try/catch
。TestWell!谢谢你的帮助!我发现问题其实是我的断开方法。非常感谢:当你的代码被编辑后,仍然会出现同样的错误,有什么想法吗?我已经添加了我的其余代码,因为这可能是您从何处触发
disconnectFromDatabase
method的问题?仅当窗体上的按钮被激活时才会调用该方法pressed@EquityEcho重新排列您的
断开与数据库的连接
,如编辑后的答案中所述!你能解释一下为什么吗?我是否正在尝试关闭已关闭的连接?