Question

I have this SqlConnection in my forms that on initialization of forms I call as following:

 public partial class options : Form
    {
        SqlConnection conn = new SqlConnection(myConnection.DataSource.ConnectionString);

This is how does look the class:

public class myConnection
{

    internal static class DataSource
    {
        private static string _ConnectionString;
        public static string ConnectionString
        {
            get
            {
                if (_ConnectionString == null)
                    _ConnectionString = FunctionToDynamicallyCreateConnectionstring();
                return _ConnectionString;
            }
        }
        private static string FunctionToDynamicallyCreateConnectionstring()
        {
                    SqlConnectionStringBuilder cb = new SqlConnectionStringBuilder();

                    cb.DataSource = Properties.Settings.Default.sql;
                    cb.InitialCatalog = Properties.Settings.Default.database;
                    cb.UserID = Properties.Settings.Default.user;
                    cb.Password = Properties.Settings.Default.pass;
                    cb.MultipleActiveResultSets = true;

                    cb.ConnectTimeout = 20;

                     return cb.ToString();

        }}

In Options form in my project I do this on button click which changes the Settings.Settings values for particular string which are later used for SqlConnectionStringBuilder

Properties.Settings.Default.sql = sql.Text;
Properties.Settings.Default.Save();

Properties.Settings.Default.database = database.Text;
Properties.Settings.Default.Save();

Properties.Settings.Default.user = user.Text;
Properties.Settings.Default.Save();

Properties.Settings.Default.pass = pass.Text;
Properties.Settings.Default.Save();

And when I'm done with changes I close the form and on FormClosed event in Form1 from which was the options form raised I do this

conn = new SqlConnection(myConnection.DataSource.ConnectionString);

Which I thought that it would change the connection string according to actual values in Properties.Settings.Default.pass etc. strings. but it doesn't.

So my question, is there possibility to change somehow the string of already inialized SqlConnection ?

Thanks in advance for your time guys.

Was it helpful?

Solution 2

Your ConnectionString is initialized only once just because you made it so:

public static string ConnectionString
{
    get
    {
        if (_ConnectionString == null)
            _ConnectionString = FunctionToDynamicallyCreateConnectionstring();
        return _ConnectionString;
    }
}

After the property is called once, the recorded value is used and is never allowed to change.

You need a "reset method"

public void ResetConnectionParams()
{
    _ConnectionString = null;
}

This way the very next time the property is called, it is allowed to rebuild parameters with new values. This means that your new connections will be created with the new, altered connection string. Make sure to call this new method somewhere!

OTHER TIPS

No. You have to close the SqlConnection and open a new one.

According to the MSDN Docs:

The ConnectionString property can be set only when the connection is closed. Many of the connection string values have corresponding read-only properties. When the connection string is set, these properties are updated, except when an error is detected. In this case, none of the properties are updated. SqlConnection properties return only those settings that are contained in the ConnectionString.

Be careful with this, as it resets many of the connection properties:

Resetting the ConnectionString on a closed connection resets all connection string values (and related properties) including the password. For example, if you set a connection string that includes "Database= AdventureWorks", and then reset the connection string to "Data Source=myserver;Integrated Security=true", the Database property is no longer set to "AdventureWorks".

The connection string for a SqlConnection can only be set via the constructor, or for an existing instance, if the SqlConnection is in the closed state (what would it mean to change the connection string for an open connection?).

If the SqlConnection is closed, you can set the connection string setting the ConnectionString property on the SqlConnection instance:

conn.ConnectionString = @"your-connection-string-here" ;

However... By default, sql connections are pooled (cached) based on the exact connection string used to construct the connection. If your app domain is long-lived, you might want to change the connection pooling configuration if you're going to be opening arbitrary connections, lest you leave open connections hanging around.

This also means that a common pattern is to construct a new connection for every query, opening and closing it for a little time as possible, something like this:

public int ExecuteSomeStoredProcudure( out DataTable dataTable )
{
    int rc ;
    string connectionString = GetConnectionString() ;
    using ( SqlConnection conn = new SqlConnection(connectionString))
    using ( SqlCommand cmd = conn.CreateCommand() )
    using ( SqlDataAdapter sda = new SqlDataAdapter())
    {
        cmd.CommandText = "someStoredProcedure" ;
        cmd.CommandType = CommandType.StoredProcedure;
        conn.Open() ;
        dataTable = new DataTable();
        rc = sda.Fill(dataTable) ;
        conn.Close() ;
    }
    return rc ;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top