limit users in the database

Asked

Viewed 71 times

0

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

What I don’t know how to do there, is to check how many already exist in DB, otherwise I do, and can not to check the id because it is possible to delete and make a new user, so the ids will pass 5

PS: I solved it like this

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();
    }
  • By limiting the number of connections in the bank would not be the system you would warn, you would have to treat an Exception coming from the bank by refusing the connection.

  • but the question is this "What I do not know how to do there, is to check how many already exist in DB"

  • You will not check, the SQL server will return an Exception saying that it can no longer execute your query and you treat the excpetion in your application.

  • what is the version of SQL Server?

  • This code seems to work, what’s going on?

1 answer

0

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

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();
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.