Click here to Skip to main content
15,885,366 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
Good afternoon people of the forum:

I was testing the validation of my connection string for the login having a SQL authentication, my idea was that if the string was correct, it would open the main form and save that connection string.


But when validating it and sending it to call the login button, regardless of whether the validation is right or wrong, it opens the main form.

If you can tell me how to validate the connection string and how to call it to my forms if it is correct.

What I have tried:

I wanted to do it using a class that builds the connection string:
    internal class Connection
    {
        public static SqlConnection Connect(string user,string password)
        {
            string string = "server=EMMANUEL\\SQLEXPRESS;database=Sales;User ID"+"="+user+";"+ "Password"+"="+password;
            SqlConnection connection = new SqlConnection(string);
            return connection;
        }
    }

    internal class Modelo
    {
        public bool Verificar_Conexion(string user, string contraseña)
        {
            bool resultado;
            try
            {
                using (SqlConnection conexion = Conexion.Conectar(user, contraseña))
                {
                    conexion.Open();
                    return resultado = true;
                }
            }
            catch
            {
                return resultado=false;
            }
        }
        
    }

internal class Control
    {
        public string ctrluser(string user, string contraseña)
        {
            Modelo modelo = new Modelo();
            string respuesta = "";

            if (string.IsNullOrEmpty(user) || string.IsNullOrEmpty(contraseña))
            {
                respuesta = "Llene todos los campos";
            }
            else
            {
                if (modelo.Verificar_Conexion(user, contraseña))
                {
                    respuesta="El usuario o contraseña son incorrectos";
                }
                
            }
            return respuesta;
        }
    }
Posted
Updated 21-May-22 19:14pm
v2

Just creating an instance of the SqlConnection object will NOT test the connection. You actually have to open the connection to try it.
 
Share this answer
 
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:
C#
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());
        }
    }
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900