limit users in the database

0

I searched and did not find out how to do to limit users in a DB ... I'm trying to make a C # application using 'sql server' and would like to know how to make userDB have a maximum of 5 users, when trying for the 6th user the system warns that it has already reached the maximum allowed ..

What I do not know to do, is to check how many already exist in DB, otherwise I do, and do not check the id because it is possible to delete and make a new user, so the ids will go from 5

PS: I solved it as well

private void btn_cadastrar_Click(object sender, EventArgs e)
    {
        sqlcon.Open();
        string sql = "SELECT COUNT(*) FROM userDB";
        SqlCommand cmd = new SqlCommand(sql, sqlcon);
        Int32 count = Convert.ToInt32(cmd.ExecuteScalar());
        if (count == 5)
        {
            MessageBox.Show("São permitidos apenas 5 usuários", "Ficha de Anamnese - ERRO", MessageBoxButtons.OK, MessageBoxIcon.Information);
        }
        else
        {
            var newuser = new cadastrodeusuario();
            newuser.Show();
            this.Hide();
        }
        sqlcon.Close();
    }
    
asked by anonymous 22.01.2018 / 19:45

1 answer

0

Your code solves the problem, but I would do otherwise, if a problem occurs the connection will stay open, and it is not doing close and dispose correctly of the objects:

int count;
using (SqlConnection con = new SqlConnection(connectionString))
{
    con.Open();
    var sql = "SELECT COUNT(*) FROM userDB";
    using (SqlCommand cmd = new SqlCommand(sql, con))
    {
        count = Convert.ToInt32(cmd.ExecuteScalar());
    }
}

if (count == 5)
{
    MessageBox.Show("São permitidos apenas 5 usuários", "Ficha de Anamnese - ERRO", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
else
{
    var newuser = new cadastrodeusuario();
    newuser.Show();
    this.Hide();
}
    
23.01.2018 / 12:07