C# - create已经成功,添加qty已经成功。但错误apears'连接已经打开。'

时间:2017-10-11 15:55:24

标签: c# mysql

人..

我正在培训创建现有的书店应用功能,以添加图书库存和减少图书库存。当我创建库存添加功能并保存库存添加的交易数据时,我收到错误'连接已经打开'。但我已经关闭了所有打开的连接。请帮帮我..

这是我显示经销商ID的代码

public void loadDistributorID()
    {
        conn.Open();

        cmd = conn.CreateCommand();
        cmd.CommandText = "select id from distributor";
        var reader = cmd.ExecuteReader();
        while (reader.Read())
        {
            distributorPasok.Items.Add(reader.GetString("id"));
        }

        conn.Close();
    }

这是我显示图书ID的代码

public void loadBukuID()
    {
        conn.Open();

        cmd = conn.CreateCommand();
        cmd.CommandText = "select id from buku";
        var reader = cmd.ExecuteReader();
        while (reader.Read())
        {
            bukuPasok.Items.Add(reader.GetString("id"));
        }

        conn.Close();
    }

这是我添加数量的代码

public void increaseQty()
    {
        conn.Open();

        cmd = conn.CreateCommand();
        cmd.CommandText = "update buku set stok=stok + @jumlah where id=@id";
        cmd.Parameters.AddWithValue("@jumlah", Convert.ToString(jumlahPasok.Value));
        cmd.Parameters.AddWithValue("@id", bukuPasok.Text);
        cmd.ExecuteNonQuery();

        conn.Close();
    }

这是我添加库存添加的交易数据的代码

try
        {
            if (distributorPasok.Text == "" || bukuPasok.Text == "" || jumlahPasok.Value == 0)
            {
                MessageBox.Show("Data harus terisi dengan valid!");
            } else
            {
                conn.Open();

                cmd = conn.CreateCommand();
                cmd.CommandText = "insert into pasok (id_distributor, id_buku, jumlah, tanggal) values (@distributor, @buku, @jumlah, @tanggal)";
                cmd.Parameters.AddWithValue("@distributor", distributorPasok.Text);
                cmd.Parameters.AddWithValue("@buku", bukuPasok.Text);
                cmd.Parameters.AddWithValue("@jumlah", Convert.ToString(jumlahPasok.Value));
                cmd.Parameters.AddWithValue("@tanggal", Convert.ToDateTime(tanggalPasok.Text));
                cmd.ExecuteNonQuery();

                MessageBox.Show("Pasok telah ditambah!");

                perbaruiPasok();

                conn.Close();
            }
        } catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
        }

我已将所有课程调入添加按钮。

1 个答案:

答案 0 :(得分:0)

连接已打开表示执行Open()方法时连接仍处于打开状态。如果你删除所有控制开放的无关线路。关闭连接,不包括相关方法的流控制语句(iftry...catch块),这就是你得到的:

// Method with try...catch
public void MethodName()
{
    try
    {
        if (...)
        {
            // other stuff
        }
        else
        {
            conn.Open(); // --> opening DB connection

            // other stuff

            conn.Close(); // --> closing DB connection
        }
    }
    catch (Exception ex)
    {
        // exception handling
    }
}

// Other method
public void OtherMethodName()
{
    // opening connection - will trigger exception if conn.Close in MethodName not executed!
    conn.Open(); 

    // other stuff

    conn.Close();
}

conn.Open()conn.Close()命令之间发生异常时,它将转到catch子句但由于conn.Close()未在此处声明,因此第二个{连接仍然打开{1}}执行。

您需要解决的问题是将conn.Open()放在finally block上,即使在conn.Close()块内发生异常,该try始终执行:

try
{
    if (...)
    {
        // other stuff
    }
    else
    {
        conn.Open();

        // other stuff
    }
}
catch (Exception ex)
{
    // exception handling
}
finally
{
    // always executed regardless of exception
    if (conn.State == ConnectionState.Open)
        conn.Close();
}

更好的方法是,建议使用using statements自动为Dispose()连接对象调用Close()方法(隐式调用IDisposable),请参阅此示例:< / p>

// declare connection string class-level instead of MySqlConnection
string connectionString = "server=localhost;database=buku;uid=fkrfdllh;pwd=*********"

try 
{
    if (empty_input)
    {
        MessageBox.Show("message text");
    }
    else
    {
        // wrap both MySqlConnection & MySqlCommand on using statements
        using (var conn = new MySqlConnection(connectionString))
        {
            conn.Open();
            using (var cmd = new MySqlCommand("[command_text]", conn))
            {
                cmd.Parameters.AddWithValue("[param_name]", value);

                // other parameters here

                cmd.ExecuteNonQuery();

                MessageBox.Show("[success_message]");

                // other methods
            }

        }
    }
}
catch (Exception ex)
{
    MessageBox.Show(ex.Message);
}

相关问题:

Why do I get a "connection is already open" error during a MySQL update statement?