Click here to Skip to main content
15,886,026 members
Please Sign up or sign in to vote.
2.00/5 (1 vote)
See more:
Is there a way to refresh a static string so you don't have restart the application?

for ex.

refresh the mysql connection string with a new user or password or host

i try it like this

What I have tried:

public static string ConnectionString(string host, string port, string user, string password, string database)
        {
           return new($"Server={host};Port={port};User Id={user};Password={password};Database={database}");
        }


private readonly MySqlConnection MySqlCore = new(ConnectionString(Data._MySQLServerHost, Data._MySQLServerPort, Data._MySQLServerUser, Data._MySQLServerPassword, Data._AuthDatabase));
Posted
Updated 28-Aug-22 19:09pm
v2

First, that is not a "static string". That is a static method that returns a string.

All you have to do is call that method again with new parameters to have a new connection string returned.

If you're calling that method once and creating a MySqlConnection object once and using it for the lifetime of the application, you have written very poor database code. You should be creating a new connection object for each database operation, and disposing of that connection object when that database operation is complete. DO NOT HOLD A CONNECTION OBJECT FOR THE LIFETIME OF THE APPLICATION!
 
Share this answer
 
To add to what Dave has said, even if your ConnectionString was a string field instead of a method, you could not change the MySqlConnection object MySqlCore anyway as it is marked as readonly which means it can be altered only at initialization or within the class constructor.

He is absolutely right about creation of a single connection object being a bad idea as well - you should construct this in a using block when you need it, do what you have to, and then let it get Closed and Disposed naturally, as you should with the DataAdapter and DataReader objects you create to use with it:
C#
using (SqlConnection con = new SqlConnection(strConnect))
    {
    con.Open();
    using (SqlCommand cmd = new SqlCommand("SELECT Age, Description FROM myTable WHERE ID = @ID", con))
        {
        cmd.Parameters.AddWithValue("@ID", myTextBox.Text);
        using (SqlDataReader reader = cmd.ExecuteReader())
            {
            while (reader.Read())
                {
                int age = (int) reader["Age"];
                string desc = (string) reader["Description"];
                Console.WriteLine($"{age}\n{desc}");
                }
            }
        }
    }
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900