无法关闭的数据库连接(MySQL)

时间:2019-04-23 12:51:35

标签: mysql database connection database-connection

经历过连接到mysql-db时有时会超时,初始连接速度非常慢等情况。

根据我的虚拟主机,我没有关闭我的连接。但是我认为我现在也找不到任何错误。请帮助mig修改我的代码或更正我的代码。

您可以在下面的代码中找到一个SelectCommand和一个ExecuteNonQuery。

List<MySqlParameter> param = new List<MySqlParameter>();
string strConnectionString = "server=mysqlXXX.loopia.se;uid=XXX;pwd=XXX;database=XXX;convert zero datetime=True";

private void ExecuteNonQuery(string strSQL, List<MySqlParameter> parameters)
{

    using (MySqlConnection connection = new MySqlConnection(strConnectionString))
    {
        connection.Open();
        using (MySqlCommand command = new MySqlCommand(strSQL, connection))
        {
            foreach (MySqlParameter param in parameters)
                command.Parameters.AddWithValue(param.ParameterName, param.Value);

            command.ExecuteNonQuery();
        }
    }
}

private DataSet getData(string query, List<MySqlParameter> parameters)
{
    using (MySqlConnection connection = new MySqlConnection(strConnectionString))
    {
        MySqlDataAdapter da = new MySqlDataAdapter();
        DataSet ds = new DataSet();

        connection.Open();
        using (MySqlCommand command = new MySqlCommand(query, connection))
        {
            foreach (MySqlParameter param in parameters)
                command.Parameters.AddWithValue(param.ParameterName, param.Value);

            da.SelectCommand = command;
        }

        da.Fill(ds);

        return ds;
    }
}

public DataSet GetSCustomers()
{
    var sql = $"SELECT * FROM Customer ";

    param.Clear();
    return getData(sql, param);
}

public void UpdateCustomerPinCode(string customerId, int pin)
{
    var sql = $"UPDATE Customer SET pin = @pin WHERE customerId = @customerId;

    param.Clear();
    param.Add(new MySqlParameter("@customerId", customerId));
    param.Add(new MySqlParameter("@pin", pin));

    ExecuteNonQuery(sql, param);
}

0 个答案:

没有答案