0

我正在使用带有 MySQL 后端的 C# 制作客户端-服务器应用程序。我试图弄清楚创建了哪些对象来增加用于 mysql 的连接。问题的根源是没有正确结束连接。

我正在寻找某种方法来检查 Visual Studio 内部/外部创建连接的所有对象。

从 MySQL 方面,我看到所有连接,以及其中有多少来自哪个客户端,但在客户端站点上,我不知道哪个对象/后台工作人员正在执行连接。

4

3 回答 3

0

我正在使用这段代码:

public DataSet MySQL_Select(string query)
        {
            MySql.Data.MySqlClient.MySqlConnection msqlConnection = null;
            msqlConnection = new MySql.Data.MySqlClient.MySqlConnection("server=" + MYSQL_SERVER + ";user id=" + MYSQL_login + ";Password=" + MYSQL_password + ";database=" + MYSQL_SCHEMAS + ";persist security info=False; Allow Zero Datetime=true ");
DataSet DS = new DataSet();
            try
             {
                MySqlDataAdapter mySqlDataAdapter = new MySqlDataAdapter(query, msqlConnection);
                mySqlDataAdapter.Fill(DS);
            }
            catch (Exception er)
            {
                MessageBox.Show(er.Message);
            }
            finally
            {
                msqlConnection.Close();
            }
            return (DS);
        }

我可以改进它吗?确保我总是密切联系,因为据我所知,finally 声明做得正确。

于 2013-10-14T13:00:41.067 回答
0

from what i read i think you want to make sure your application only opens 1 connection and make sure that connection is closed properly.

I am using a class to connect to the database which simply has a select method which opens and closes the connection, the beauty of this is you don't need singletons or need to worry about multiple threads since when ever the select method is executed the connection is closed automatically:

/// <summary>
/// class which controlls the database, 
/// </summary>
public class DBConnect
{
    private MySqlConnection connection;

    /// <summary>
    /// the constructor which starts to initialize the database.
    /// </summary>
    /// <param name="username"></param>
    /// <param name="password"></param>
    public DBConnect(string username, string password)
    {
        Initialize(username, password);
    }

    /// <summary>
    /// initiates connection string for the database.
    /// </summary>
    /// <param name="username"></param>
    /// <param name="password"></param>
    private void Initialize(string username, string password)
    {
        string server = "Localhost";

        string database = "";
        string connectionString;
        connectionString = "SERVER=" + server + ";" + "DATABASE=" +
        database + ";" + "UID=" + username + ";" + "PASSWORD=" + password + ";";

        connection = new MySqlConnection(connectionString);
    }


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

                //case 1045:
                //    MessageBox.Show("Invalid username/password, please try again");
                //    break;
            }
            MessageBox.Show(ex.Message + "\r\n" +
                ex.StackTrace);
            return false;
        }
        catch (InvalidOperationException ioe)
        {
            Console.WriteLine(ioe);
            MessageBox.Show("Er is al een connectie geopend");
            return false;
        }
    }

    /// <summary>
    /// closes the connection with the database
    /// </summary>
    /// <returns>true or false depending on the succes of closing the connection</returns>
    private bool CloseConnection()
    {
        try
        {
            connection.Close();
            return true;
        }
        catch (MySqlException ex)
        {
            Console.WriteLine(ex.Message);
            return false;
        }
    }

    /// <summary>
    /// generally used to get multpile rows of data from the datbase
    /// </summary>
    /// <param name="query">SQL statement</param>
    /// <returns></returns>
    public DataTable Select(MySqlCommand cmd)
    {
        //Open connection
        if (this.OpenConnection() == true)
        {
            //Create Command
            cmd.Connection = connection;

            //Read the data and store it in a DataTable
            DataTable dt = new DataTable();
            MySqlDataAdapter da = new MySqlDataAdapter(cmd);
            try
            {
                da.Fill(dt);
            }
            catch (MySqlException e)
            {
                MessageBox.Show("An exception has occured loading the data: \n" + e.Message);
                Console.WriteLine(e.Message);
            }

            //close Connection
            this.CloseConnection();

            //return list to be displayed
            return dt;
        }
        else
        {
            return null;
        }
    }
}
于 2013-10-14T11:34:24.583 回答
0

As alluded to by Steve's comment, wrap with a using block; this will close and dispose of the connection object as soon as it's out of scope.

using (IDbConnection conn = new MySql.Data.MySqlClient.MySqlConnection(...))
{
    using (IDbCommand cmd = new MySql.Data.MySqlClient.MySqlCommand("select ...", conn))
    {
        conn.Open();

        var reader = cmd.ExecuteReader()';
        // process reader, etc
    }
}

IDisposable implementers should be inside a using.
IDbConnections should not be global variables, they should be constructed, used and disposed in scope, or passed into methods as parameters.

于 2016-11-09T10:24:35.520 回答