如果在C#中禁用= 0则更新

时间:2016-02-07 15:27:24

标签: c# sql-server sqldatareader sqlcommand

我正在C#制作一个项目 - 其中一个人可以“投票”。

当您运行程序时,首先登录。登录后,您必须从下拉列表中选择一个值。选择教师后,按下投票的按钮。

问题是我真的不知道如何正确验证。并检查该人是否已经投票。

如果值= 1或0,则必须检查名为“disabled”的数据库中的列。如果值= 1则无法投票,如果为0,则可以。

当此人投票时,将列aantalStemmen增加1.并将disabled列增加为1。哪个在datagridview中显示。

下拉列表中的值必须与数据库中的1匹配。

我有这段代码:

 private void db_connection()
    {
        try
        {
            conn = "Data Source=localhost;Initial Catalog=docent;Integrated Security=True";
            connect = new SqlConnection(conn);
            connect.Open();
        }
        catch (SqlException e)
        {
            throw;
        }
    }
    private bool validate_disabled(string favoriet)
    {
        db_connection();
        SqlCommand cmd = new SqlCommand();
        cmd.CommandText = "Select disabled from leerling";
        cmd.Connection = connect;
        SqlDataReader disabled = cmd.ExecuteReader();
        if (disabled.Read())
        {
            connect.Close();
            return true;
        }
        else
        {
            connect.Close();
            return false;
        }
    }



    private void btnStem_Click(object sender, EventArgs e)
    {
        string favoriet = cmbFavoriete.Text;

        db_connection();
        SqlCommand cmd = new SqlCommand();

        bool r = validate_disabled(favoriet);

        if(r){

        cmd.CommandText = "UPDATE docent SET aantalStemmen = aantalStemmen + 1 where docentid=@id";
        cmd.Parameters.AddWithValue("@id", cmbFavoriete.Text);
        }
        else
        {
MessageBox.Show("You have already voted.");
        }

    }

我的数据库中的表格如下所示:

Table leerling

Table Docent

在此先感谢,我一直在努力奋斗,因为我还是C#的新秀。

2 个答案:

答案 0 :(得分:1)

我建议您在表格中使用bit数据类型(0 - false,1 - true)而不是int数据类型。它完全符合您的需求,您不必为此使用int

这意味着您可以将validate_disabled方法更改为使用以下内容:

cmd.CommandText = "SELECT disabled FROM leerling WHERE disabled = 1 AND leerlingnummer = @favoriet";
cmd.Parameters.AddWithValue("@favoriet", favoriet);

我假设字符串favoriet等于您表格中的leerlingnummer。在您执行该查询后,您只需检查查询是否包含多于0条记录 - 如果超过0条记录,则表示此人无权投票。

答案 1 :(得分:1)

我将尝试回答您的代码的更多方面(许多已经在评论中提到过):

1)在您的方法之外声明您的连接字符串。同时选择有意义的变量名称 - 当您重新访问代码时,您将在几个月内完成。

private const String ConnectionStr = "Data Source=localhost;Initial Catalog=docent;Integrated Security=True";

<强> 2。方法的适当名称 - 同样,尝试使用Camel或Pascal案例作为方法名称。

第3。在构造或打开SqlConnection时,请注意可能的异常。 SQLExceptionnot the only possible exception,因此最好抓住可能发生的任何事情

private SqlConnection createConnection
{
   try
    {
        connect = new SqlConnection(ConnectionStr);
        connect.Open();
    }
    // this is laziness, but it is better than before 
    catch (Exception e)
    {
        // best to log the real error somewhere
        throw;
    }
}

<强> 4。处理连接和其他一次性用品,如SqlCommand 。 var也可以保存一些输入(只需将鼠标悬停在关键字上,您就会看到实际类型)。

SqlConnection允许使用CreateCommand直接创建使用该特定连接执行的命令。

由于您期望单个值(标量)(或具有单个列的单行),因此您可以使用ExecuteScalar方法。所以,没有更多的读者。

private bool isDisabled(string favoriet)
{
    using (var connection = createConnection())
    {
        using (var cmd = new connection.CreateCommand())
        {
            cmd.CommandText = "Select disabled from leerling where leerlingnummer = @number";
            cmd.Parameters.AddWithValue("@number", favoriet);

            // for simplicity I have assumed that it will always find a value. This should be checked
            var disabled = Convert.ToBoolean(cmd.ExecuteScalar());
            return disabled;
        }
    }
}

<强> 5。尽量不要将UI逻辑与数据库逻辑混合(它们通常放在不同的程序集中)

private void castVote(String favoriete)
{
    using (var connection = createConnection())
    {
        using (var cmd = new connection.CreateCommand())
        {
            cmd.CommandText = "UPDATE docent SET aantalStemmen = aantalStemmen + 1 where docentid = @id";
            cmd.Parameters.AddWithValue("@id", cmbFavoriete.Text);
            // command must be actually executed, otherwise nothing happens
            cmd.ExecuteNonQuery();
        }
    }
}

private void btnStem_Click(object sender, EventArgs e)
{
    string favoriet = cmbFavoriete.Text;

    bool r = isDisabled(favoriet);

    if (r) 
        castVote(favoriet);
        // maybe, it would make sense to also notify the user that the vote has been cast
    else
        MessageBox.Show("You have already voted.");
}

<强> 6。使用EntityFramework - 为了避免与处理命令和阅读器相关的麻烦,您可以使用ORM为您执行脏工作。