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:
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}");
}
}
}
}