Frage

Maybe simple question, but right now I am having hard time imagining the object oriented concept on this example. I have defined my MySqlConnection in one separate class in c# (separate /.cs/ file).

 class MySQLConnect
{


    public bool ConnectToMySQL()
    {


        string cs = @"server=127.0.0.1; user id=root; password=''; database=cluster";

        MySqlConnection conn = null;

        try
        {
            conn = new MySqlConnection(cs);
            conn.Open();
            MessageBox.Show("Pripojené k DB : {0}", conn.ServerVersion);
        }
        catch (MySqlException ex)
        {
            MessageBox.Show("Error: {0}", ex.ToString());

        }

        return true;
    }
}

In the form class I have defined connection object like this:

 MySQLConnect con = new MySQLConnect();

Now, I am calling the ConnectToMySQL method on a button click in my form class:

private void button1_Click(object sender, EventArgs e)
    {

        con.ConnectToMySQL();

    }

Lets say, that I would like to have another separate class, which will have a method that will perform some sql queries. This method will also be called on a button click. How should I use the established connection from MySQLConnect class in my new class?

Thank you.

War es hilfreich?

Lösung

You may declare a SqlConnection field in your class like that

    static class MySQLConnect
    {
            private static SqlConnection _Connection;
            public static SqlConnection Connection
            {
                    get
                    {
                            if(_Connection == null)
                            {
                                    string cs = @"server=127.0.0.1; user id=root; password=''; database=cluster";
                                    _Connection = new MySqlConnection(cs);
                            }

                            if(_Connection.State == ConnectionState.Closed)
                                    try
                                    {
                                                conn.Open();
                                    }
                                    catch(Exception ex)
                                    {
                                            //handle your exception here
                                    }
                            return _Connection;
                    }
            }
    }

you can then access your SqlConnection in old your project using

    SqlConnection myConnection = MySQLConnect.Connection;

It's a quick example that suffers from having the connection opened during all the time of your project while it would be better to only open and close it through methods like "Open" and "Close" in your class.

so I'd suggest create a MyConnect class Singleton and use a non static SqlConnection object so you'll be able to make that better.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top