我的程序运行,它最初成功连接到数据库。我可以运行查询,一切正常。但是,我似乎无法断开连接并重新连接到数据库。输出说:“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;
}
}
}
答案 0 :(得分:2)
在finally
中加入try/catch
块以关闭连接。另外,我建议使用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;
}
答案 1 :(得分:0)
我认为您希望if语句为
//THIS IS WHERE I GET STUCK THE SECOND TIME
if (cnn.State == ConnectionState.Open)
{
cnn.Close();
cnn.Open();
}
使用!=如果连接未打开,则只调用cnn.Close()。
答案 2 :(得分:0)
您的try/catch
阻止没有关闭您的连接。负责关闭与finally
块的连接。即使程序中发生任何异常,它也会关闭连接。请尝试以下...
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;
}
答案 3 :(得分:0)
您似乎尝试关闭抛出异常的已关闭连接:
if (cnn.State == ConnectionState.Open)
{
cnn.Close();
}
cnn.Open();
如果连接已经打开,请尝试上面关闭连接,然后将其打开