gpt4 book ai didi

c# - 为什么不能在一个方法中调用两次 OpenConnection()?

转载 作者:行者123 更新时间:2023-11-29 06:50:12 32 4
gpt4 key购买 nike

为什么我不能在一个方法中调用两次 OpenConnection()?当我调用它时出现此错误:

The connection is already open.

我在SelectDisPatient()中调用了两次和 Count() .在 for (int index = 0; index < Count(); index++) 查看我的代码

这个方法SelectDisPatient :

public void SelectDisPatient(FrmVIRGO frm)
{
string query = "SELECT id_pasien FROM tb_patient_information ";
if (this.OpenConnection() == true)
{ //Create Command
MySqlCommand cmd = new MySqlCommand(query, connection);
//Create a data reader and Execute the command
MySqlDataReader dataReader = cmd.ExecuteReader(CommandBehavior.CloseConnection);
if (dataReader.HasRows)
{
for (int index = 0; index < Count(); index++)
dataReader.Read();
frm.tbName.Text = dataReader[0].ToString();
}
//close Data Reader
dataReader.Close();

//close Connection
this.CloseConnection();

}
}

Count()方法:

public int Count()
{
string query = "SELECT Count(*) FROM tb_patient_information";
int Count = -1;

//Open Connection
if (this.OpenConnection() == true)
{
//Create Mysql Command
MySqlCommand cmd = new MySqlCommand(query, connection);

//ExecuteScalar will return one value
Count = int.Parse(cmd.ExecuteScalar()+"");

//close Connection
this.CloseConnection();

return Count;
}
else
{
return Count;
}
}

但是当我删除 (this.OpenConnection() == true)Count()它说我需要关闭连接的方法。

最佳答案

尝试:

public void SelectDisPatient(FrmVIRGO frm)
{
int count = Count();
string query = "SELECT id_pasien FROM tb_patient_information ";
if (this.OpenConnection() == true)
{ //Create Command
MySqlCommand cmd = new MySqlCommand(query, connection);
//Create a data reader and Execute the command
MySqlDataReader dataReader = cmd.ExecuteReader(CommandBehavior.CloseConnection);
if (dataReader.HasRows)
{
for (int index = 0; index < count ; index++)
dataReader.Read();
frm.tbName.Text = dataReader[0].ToString();
}
//close Data Reader
dataReader.Close();

//close Connection
this.CloseConnection();

}
}

关于c# - 为什么不能在一个方法中调用两次 OpenConnection()?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15931381/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com