Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8614341
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 12, 20262026-06-12T05:05:59+00:00 2026-06-12T05:05:59+00:00

I have a simple C# MySQL connection class as: using System; using System.Data; using

  • 0

I have a simple C# MySQL connection class as:

using System;
using System.Data;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Text;
using System.Diagnostics;
using System.IO;
using MySql.Data.MySqlClient;


namespace FSB
{
    public class DBConnect
    {
        private MySqlConnection connection;
        private string server;
        public string port;
        private string database;
        private string uid;
        private string password;

        //Constructor
        public DBConnect()
        {
            Initialize();
        }

        ~DBConnect()
        {
            //close connection
            this.CloseConnection();

        }


        //Initialize values
        private void Initialize()
        {



           // Local Database
            server = "localhost";
            database = "mydatabase";
            uid = "user";
            password = "pass";


            string connectionString;
            connectionString = "SERVER=" + server + ";Port=" + port + ";" + "DATABASE=" + database + ";" + "UID=" + uid + ";" + "PASSWORD=" + password + ";";

            connection = new MySqlConnection(connectionString);
        }


        //open connection to database
        private bool OpenConnection()
        {
            try
            {
                connection.Open();
                return true;
            }
            catch (MySqlException ex)
            {
                //When handling errors, you can your application's response based on the error number.
                //The two most common error numbers when connecting are as follows:
                //0: Cannot connect to server.
                //1045: Invalid user name and/or password.
                switch (ex.Number)
                {
                    case 0:
                        Console.WriteLine("Cannot connect to server.  Contact administrator");
                        break;

                    case 1045:
                        Console.WriteLine("Invalid username/password, please try again");
                        break;
                }
                return false;
            }
        }

        //Close connection
        public bool CloseConnection()
        {
            try
            {
                if (connection.State == System.Data.ConnectionState.Open)
                {
                    connection.Close();
                    connection.Dispose();
                }
            }
            catch (MySqlException ex)
            {
                Console.WriteLine(ex.Message);
                return false;
            }
            return true;
        }

        //Insert statement
        public void Insert(String query)
        {

            //open connection
            if (this.OpenConnection() == true)
            {
                //create command and assign the query and connection from the constructor
                MySqlCommand cmd = new MySqlCommand(query, connection);

                //Execute command
                cmd.ExecuteNonQuery();

                //close connection
                this.CloseConnection();
            }
        }

        //Update statement
        public void Update(string query)
        {

            //Open connection
            if (this.OpenConnection() == true)
            {
                //create mysql command
                MySqlCommand cmd = new MySqlCommand();
                //Assign the query using CommandText
                cmd.CommandText = query;
                //Assign the connection using Connection
                cmd.Connection = connection;

                //Execute query
                cmd.ExecuteNonQuery();

                //close connection
                this.CloseConnection();
            }
        }

        //Delete statement
        public void Delete(string query)
        {

            if (this.OpenConnection() == true)
            {
                MySqlCommand cmd = new MySqlCommand(query, connection);
                cmd.ExecuteNonQuery();
                this.CloseConnection();
            }
        }

        public MySqlDataReader getRecord(string query)
        {

            if (this.OpenConnection() == true)
            {
                //create mysql command
                MySqlCommand cmd = new MySqlCommand();
                MySqlDataReader reader;

                //Assign the query using CommandText
                cmd.CommandText = query;
                //Assign the connection using Connection
                cmd.Connection = connection;

                //Execute query
                reader = cmd.ExecuteReader();
                return reader;
            }

            return null;

        }


        //Check Duplicate statement  return true if not found
        public bool checkDuplicate(string tableName ,String fieldName,String checkValue)
        {

            //Open connection
            if (this.OpenConnection() == true)
            {
                //create mysql command
                MySqlCommand cmd = new MySqlCommand();
                MySqlDataReader reader;
                int rowCount = 0;

                //Assign the query using CommandText
                String query = "Select * from `" + tableName + "` Where  `"+fieldName + "` = '"+ checkValue +"'";
                cmd.CommandText = query;
                //Assign the connection using Connection
                cmd.Connection = connection;

                //Execute query
                reader =  cmd.ExecuteReader();
                while (reader.Read())
                {
                    //get rows
                    rowCount++;
                }
                //close connection
                this.CloseConnection();

                if (rowCount > 0)
                {
                    return false;
                }


            }
            return true;
        }

    }
}

Can anyone please where I am losing the connection as the connection remains open even after the object is out of scope every time the i use to do any operation a new connection is created and a previous connection is not closed. so I am running out of the connection limit to mysql ?

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-12T05:06:00+00:00Added an answer on June 12, 2026 at 5:06 am

    I suggest you to use using blok in order to clean your non managed object, your connection in this sample

    using (var connection = new MySqlConnection("..."))
    {
       ....
    }
    

    Nota : using blok execute dispose in the end of treatment in roder to clean

    public void Insert(String query)
     {
            using(var connection = new MySqlConnection("..."))
            {
                connection.Open();
                using(var  cmd = new MySqlCommand(query, connection))
                {
                    cmd.ExecuteNonQuery();
                }
            }
      }
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have a simple MySQL table for storing notification in a web with social
I have problem with creating a simple MySQL trigger in C#. I'm using StringBuilder
I have a simple query (in a mySQL view) that php is using to
I develop web applications with PHP. I have many classes using a database connection.
I have simple line class autorization extends mysql and it causes Fatal error: Call
We have a small java based server (a simple app which fetches data using
I have a simple MySQL table thats contains a list of categories, level is
I have a very simple MySQL table Name | Time | Count James |
I have got a simple MySQL table and primary index (id) is not numbered
I currently have a very simple MySQL database (articlesDB) with 1 table (articles) and

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.