【问题标题】:How can i prevent duplicate insert datas from date in my attendance如何防止在我的出席日期中重复插入数据
【发布时间】:2019-03-07 10:11:59
【问题描述】:

大家好,晚上好,我有一个问题.. 我怎样才能防止重复插入数据到我的数据库。我的逻辑是他早上进来,日期是 2019 年 3 月 7 日 他插入,当他在 2019 年 3 月 7 日再次尝试加入时,消息框将显示(“他已经加入”),当他在 2019 年 3 月 8 日时,简而言之,如果他现在可以加入,他可以再次加入又是一天,我该如何解决这个问题,我这里有一些代码

 MySqlDataReader dr;
        if (con != null && con.State == ConnectionState.Closed)
        {
            con.Open();
        }
        MySqlCommand cmd = new MySqlCommand("Select * from attendance1 where empID=@empID AND Name=@Name AND Date=@Date", con);
        cmd.Parameters.Add("@empID", MySqlDbType.VarChar).Value = empID.ToString();
        cmd.Parameters.Add("@Name", MySqlDbType.VarChar).Value = label6.Text;
        cmd.Parameters.Add("@Date", MySqlDbType.Date).Value = Convert.ToDateTime(label4.Text);

        dr = cmd.ExecuteReader();

        if (dr.Read())
        {
            MessageBox.Show("You are already In");

        }
        else
        {

            MySqlCommand cmd1 = new MySqlCommand("INSERT INTO attendance1(empID,Name,Date,MorningIn)values(@empID,@Name,@Date,@MorningIn)", con);
            cmd1.Parameters.Add("@empID", MySqlDbType.VarChar).Value = empID.ToString();
            cmd1.Parameters.Add("@Name", MySqlDbType.VarChar).Value = label6.Text;
            cmd1.Parameters.Add("@Date", MySqlDbType.Date).Value = Convert.ToDateTime(label4.Text);
            cmd1.Parameters.Add("@MorningIn", MySqlDbType.VarChar).Value = label2.Text;
            cmd1.ExecuteNonQuery();
            MessageBox.Show("OK");


        }
        if (con != null && con.State == ConnectionState.Open)
        {
            con.Close();
        }

因为连接打开而出错...我可以采取什么策略?

【问题讨论】:

  • 删除第二个con.Open(),并为最佳实践在您的连接周围使用using ( )。然后你应该能够执行你的两个命令。问题是您遇到 SQL 问题还是您的查询不起作用?
  • @NibblyPig 我这样做了,但错误仍然是连接打开

标签: c# mysql database


【解决方案1】:

你在这里打开了两次连接,

1) 删除所有con.Open(); and con.Close()

2) 在MySqlDataReader dr之后添加;

if (con != null && con.State == ConnectionState.Closed)
{
   con.open();
}

3) 在最后一个命令行中写入

 if (con != null && con.State == ConnectionState.Open)
{
   con.close();
}

【讨论】:

  • 在最后一个 cmd1 的 else 中 con.close?
  • if{}else{} then if (con != null && con.State == ConnectionState.Open) { con.close(); }?
  • 你将在你的 if 和 else 中使用连接,所以你应该在之前打开你的连接, if (con != null && con.State == ConnectionState.Closed) { con.open (); } IF {} ELSE{} if (con != null && con.State == ConnectionState.Open) { con.close(); }
  • 我在顶部编辑我的代码。 AhmadMM 先生说的对吗?
  • 如果您在任何操作之前打开连接并在连接没有任何问题后关闭它
猜你喜欢
  • 2015-10-06
  • 2016-04-11
  • 2021-11-23
  • 1970-01-01
  • 2012-01-06
  • 1970-01-01
  • 1970-01-01
  • 2023-03-06
  • 1970-01-01
相关资源
最近更新 更多