Search code examples
c#database-connection3-tier

Getting trouble in Login Page 3-Tire architecture


Bussiness Access Layer :

    public static int login(string userlogin, string pwdlogin)
    {
        SqlConnection con = new SqlConnection();
        con.ConnectionString = GetConnectionString();
        con.Open();
        int id = 0;
        string selectstr = "SELECT UserName, Password FROM Registration WHERE UserName = '" + userlogin.Trim() + "' AND Password = '" + pwdlogin.Trim() + "'";
        SqlCommand cmd = new SqlCommand();
        cmd.CommandText = selectstr;
        cmd.CommandType = System.Data.CommandType.Text;
        cmd.Connection = con;
        id = cmd.ExecuteNonQuery();
        cmd = null;
        con.Close();
        return id;
    }

Login.cs

 protected void Button1_Click(object sender, EventArgs e)
    {
        int id = BusinessAccessLayer.login(userlogin.Text.Trim(), pwdlogin.Text.Trim());
        if (id > 0)
        {
            message.Text = " valid";
        }
        else
        {
            message.Text = "in valid";
        }   
    }

Solution

  • The ExecuteNonQuery is used for For UPDATE, INSERT, and DELETE statements. For SELECT statements, use ExecuteReader

    public static int login(string userlogin, string pwdlogin)
    {
            SqlConnection con = new SqlConnection();
            con.ConnectionString = GetConnectionString();
            con.Open();
            int id = 0;
            string selectstr = "SELECT UserName, Password FROM Registration WHERE UserName = '" + userlogin.Trim() + "' AND Password = '" + pwdlogin.Trim() + "'";
            SqlCommand cmd = new SqlCommand();
            cmd.CommandText = selectstr;
            cmd.CommandType = System.Data.CommandType.Text;
            cmd.Connection = con;
            SqlDataReader reader = cmd.ExecuteReader();
            while (reader.Read())
            {
                   id++; 
            }
            cmd = null;
            reader.Close();
            con.Close();
            return id;
    }