To add to what Dave has - rightly - said: it's a very bad idea to hard code your connection string at all. When you do that, even if it is only used in one place it means that when you move to production you need to change the software for each site, and release software that is untested. You should store it in a configuration file, either the XML based settings file myappname.exe.config or a human editable file of your choice.
This is how I do it:
Instance Storage - A Simple Way to Share Configuration Data among Applications[
^] but that may be overkill for your project.
I'd also strongly suggest that you don't do it like that at all: even if you do open the connection for testing in your
Verificar_Conexion
method, you don't close it again, you don't Dispose of it anywhere, and you can't use a
using
block to ensure that the connection object is automatically closed and disposed when you are finished with it. SQL connections are a scarce resource, and need to be deleted as soon as you are finished with them - and not kept open for the life of the application!
Plus, creating a single connection object and "recycling" it has it's own problems: if you accidentally leave a SqlDataReader open then you can't do anything else with the connection until it is closed.
Create your connection in a
using
block when you need it (and SqlCommand objects etc. as well) and it is all handled for you automatically:
string strConnect = SMDBSupport.SMInstanceStorage.GetInstanceConnectionString("MyDatabaseName");
string sql = "SELECT Id, Desc FROM MyTable";
using (SqlConnection con = new SqlConnection(strConnect))
{
try
{
con.Open();
using (SqlCommand cmd = new SqlCommand(sql, con))
{
using (SqlDataReader read = cmd.ExecuteReader())
{
while (read.Read())
{
int id = (int)read[0];
string desc = (string) read[1];
}
}
}
}
catch (Exception ex)
{
Debug.WriteLine(ex.ToString());
}
}