我想限制用户每天只插入一次他的表演

时间:2014-06-26 09:48:28

标签: c# sql-server restriction

我编写了这段代码,但它允许用户每天多次输入他们的性能记录,而我想要的是用户每天只能这样做一次。

起初我写了这样的条件:if (dt.Rows.Count < 0)但在这种情况下只有部分工作,用户不能至少输入一次他的记录..

 protected void subtbtn_Click(object sender, EventArgs e)

    {
        DataTable dt = new DataTable();

        SqlConnection connection = new SqlConnection(@"Data Source=.\sqlexpress;Initial Catalog=incible;Integrated Security=true");

        connection.Open();

        string sqlStatement = "SELECT * FROM prfrmnce where u_name='" + unamelbl.Text + "' and datetime ='" + Calendar1.TodaysDate + "'";

        SqlCommand cmd1 = new SqlCommand(sqlStatement, connection);

        SqlDataAdapter sqlDa = new SqlDataAdapter(cmd1);

         sqlDa.Fill(dt);

         if (dt.Rows.Count == 0)

         {
             // Open the database connection

             string myConnectionString = @"Data Source=.\sqlexpress;Initial Catalog=incible;Integrated Security=true";

             SqlConnection con = new SqlConnection(myConnectionString);
             con.Open();
             //Query to insert images name and Description into database
             SqlCommand cmd = new SqlCommand("Insert into prfrmnce(u_name,designatn,datetime,todaytask,tmrwplan) values(@uname,@dsgntn,@date,@twrk,@tmrwpln)  ", con);
             //Passing parameters to query
             cmd.Parameters.AddWithValue("@uname", UserName.Text);
             cmd.Parameters.AddWithValue("@dsgntn", desigtxtbx.Text);
             cmd.Parameters.AddWithValue("@twrk", tfortday.Text);
             cmd.Parameters.AddWithValue("@tmrwpln", pfortmrw.Text);
             cmd.Parameters.AddWithValue("@date", Calendar1.TodaysDate);

             cmd.ExecuteNonQuery();
             resultlebel.Text = "data added successfully";

             //Close dbconnection


             con.Close();
             tfortday.Text = string.Empty;
             pfortmrw.Text = string.Empty;
             GridView1.DataBind();
         }
         else if (dt.Rows.Count > 0) 
         {
             errorlabel.Text = "You have already submitted your today's performance";
         }


    }

2 个答案:

答案 0 :(得分:2)

我猜这是一个DateTime问题。 DateTime不是一天,它还有小时,分钟等。

您应该只使用日期的日期部分。

所以在你的查询中,

变化

and datetime ='" + Calendar1.TodaysDate + "'"

and cast(datetime as date) = '" + Calendar1.TodaysDate.Date + "'"

顺便说一下,你应该使用参数,而不是字符串连接。msdn

答案 1 :(得分:0)

此查询是否正确...

string sqlStatement = "SELECT * FROM prfrmnce where u_name='" + unamelbl.Text + "' and datetime ='" + Calendar1.TodaysDate + "'";

问题可能是Calendar1.TodaysDate给出了日期和时间,所以你总是得到dt.Rows.Count为0