0

我有一个简单的 C# MySQL 连接类:

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;
        }

    }
}

任何人都可以请我失去连接的地方,因为即使在每次我用来执行任何操作时对象超出范围后,连接仍保持打开状态,创建新连接并且未关闭先前的连接。所以我的mysql连接限制用完了

4

1 回答 1

2

我建议你使用using blok为了清理你的非托管对象,你在这个示例中的连接

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

注意:在roder的治疗结束时使用blok执行dispose来清洁

public void Insert(String query)
 {
        using(var connection = new MySqlConnection("..."))
        {
            connection.Open();
            using(var  cmd = new MySqlCommand(query, connection))
            {
                cmd.ExecuteNonQuery();
            }
        }
  }
于 2012-10-02T09:45:21.107 回答