An alternative answer in the question Different connectionstring for different builds you can use the Directives for pre-processing.
"The #if, #Elif, #Else, and #endif directives are used in conditional preprocessing, for example, to check whether a symbol or symbols are true." that is, the line is only compiled according to the configured mode - Release or Debug.
To create a connection string conditioned to different banks (Production and Approval), use the #if (DEBUG)
, follow the steps:
Now in your code, you will do the following:
using System;
using System.Data;
using System.Data.SqlClient;
using System.Web.UI;
public partial class _Default : Page {
private string connectionString;
protected void Page_Load(object sender, EventArgs e) {
#if (DEBUG) //Ao compilar em modo DEBUG, a variável receberá o valor abaixo
connectionString = "Data Source=seu_servidor;" +
"Initial Catalog=seu_banco_de_HOMOLOGACAO;" +
"User ID=seu_usuario; " +
"Password=sua_senha";
#else
connectionString = "Data Source=seu_servidor;" +
"Initial Catalog=seu_banco_de_PRODUCAO;" +
"User ID=seu_usuario; " +
"Password=sua_senha";
#endif
}
internal void ConexaoBanco() {
using (SqlConnection conn = new SqlConnection(connectionString)) {
string query = "SELECT * FROM DBO.TABELA";
using (SqlCommand cmd = new SqlCommand(query, conn)) {
DataTable tabelaTeste = new DataTable("tabelaTeste");
SqlDataAdapter dataAdapter = new SqlDataAdapter(cmd);
conn.Open();
dataAdapter.Fill(tabelaTeste);
conn.Close();
}
}
}
}
Note: Likewise this can be done in Windows Forms.
#if (reference of C#)
Possible duplicate of Different connectionstring for different builds
– Randrade
Hello Simon, consider accepting my answer if it has been useful to you. If you think she’s incomplete or doesn’t respond to you, make the appropriate comments so I can improve her.
– Ismael