Create a variable connection string. How do I use it now? [closed]

0

I'm not sure how to make this possible, so I'd like some advice since I'm new to managing connections in this language.

In my code I use the following string to connect to SQL SERVER;

WEB.Config

 <connectionStrings>
  <add name="Primaria" connectionString="Data Source=LAPTOP- 
   DDBTHB5L\SQLEXPRESS;Initial Catalog=DEMO;Integrated Security=SSPI"/>
  </connectionStrings>

.CS

   private string connectionString = 
   WebConfigurationManager.ConnectionStrings["Primaria"].ConnectionString;

My problem now is that I develop a new connection string and store it in a variable called scon.

// part of the code

 protected void cadena(object sender, EventArgs e)
{ 

      //
      //
      //


               Servidor = dr["Servidor"].ToString();
                BD = dr["Nombre_BD"].ToString();
            }
        }
        dr.Close();
        string constr = "Data Source ="+Servidor+"; Initial Catalog ="+BD+"; Integrated Security = SSPI";

        Session["scon"] = scon;


}

How do I use the new one that I defined in the following code ?, since I occupy the 2, and in the way that this now only connects me to the web.config.

{


    string SQLFamilia = "SELECT Nombre from Alumnos"; ;

    SqlConnection con = new SqlConnection(connectionString);
    SqlCommand cmd = new SqlCommand(SQLAlumnos, con);
    SqlDataReader reader;
    
asked by KJSK 25.07.2018 в 07:22
source

1 answer

1

You can dynamically add a CNN String to your WebConfigurationManager.ConnectionStrings , which you can then read during the execution of the program (the webconfig file is not modified).

Configuration config = WebConfigurationManager.OpenWebConfiguration(null);
config.ConnectionStrings.ConnectionStrings.Add(new ConnectionStringSettings("mycustonstringName","mycustonstringValue"));

Then you simply retrieve it as if you were reading from the webconfig.

var myCustomCnnString = WebConfigurationManager.ConnectionStrings["mycustonstringName"].ConnectionString;
    
answered by 25.07.2018 в 17:33