Home > Net >  Can I use same connection in my mainwindow in other windows? C# wpf mysql [duplicate]
Can I use same connection in my mainwindow in other windows? C# wpf mysql [duplicate]

Time:09-21

I have a problem, I am working on a C# WPF project which I need to connect to the MySQL database. I used to work with SQL Server with C# but since I need this project to upload/read data from an online databases I have to use MySQL, so I search on the net and find this solution:

using MySql.Data.MySqlClient;
    
connString = "SERVER=localhost;PORT=3306;DATABASE=test;UID=root;PASSWORD=;SslMode=none;";
            try
            {
                conn = new MySqlConnection();
                conn.ConnectionString = connString;
                conn.Open();
                MessageBox.Show("Connection Success");
            }
            catch (MySql.Data.MySqlClient.MySqlException ex)
            {
                MessageBox.Show(ex.Message);
            }

I use it in my main window and it worked, now I have another question which is how can I use this connection on their windows? should I use the same code in all windows? or I can use it from the main window? for example, I have a DATAGRID in another window and I need to read the data from the database into the DATAGRID. how is this possible?

CodePudding user response:

C# database connection objects are not thread-safe. When you need one, you should create it, open it, use it, close it, and dispose it. You can do this from any code anywhere in your app. But don't try to keep a connection cache.

That seems like an absurd amount of overhead, but it's not. The database connection object code maintains a pool of open connections: when your code stops using a connection (by closing and disposing it) it goes back into the pool. From there it is reused by the next code requesting the same connection.

In this respect the MySql connector works the same way as the Microsoft-furnished SQL Server connector.

  • Related