如何在c#中插入更新后插入相同的id

时间:2018-03-05 17:51:13

标签: mysql-workbench c#

我正在尝试创建一个考勤项目。我正在使用update&我的代码中insert。请检查下面的代码。我知道我很容易受到SQL注入。

我的问题是当我尝试使用相同的ID时,即使我使用相同的ID超时,它也会显示超时的时间。知道如何再次使用相同的ID吗?

MySqlCommand cmd = new MySqlCommand("SELECT * FROM tbl_student_list INNER JOIN attendance_tbl On  tbl_student_list.ID = attendance_tbl.stud_id   WHERE stud_id ='" + dataGridView1.Rows[i].Cells["Column1"].Value + "'", conn);
cmd.Parameters.AddWithValue("stud_id", dataGridView1.Rows[i].Cells["Column1"].Value);
conn.Open();
MySqlDataReader DataRead = cmd.ExecuteReader();
DataRead.Read();

这是我的更新代码:

 //If already Time-In execute Time-Out


 if (DataRead.HasRows)
  {
  dataGridView1.Rows[i].Cells["Column3"].Value = DataRead[1].ToString();
  dataGridView1.Rows[i].Cells["Column4"].Value = DataRead[2].ToString();
  dataGridView1.Rows[i].Cells["Column2"].Value = DateTime.Now.ToString("yy/MM/dd");
  byte[] images = ((byte[])DataRead[3]);

   if (images == null)
   {
      pictureBox1.Image = null;
    }
    else
    {
    MemoryStream mstreem = new MemoryStream(images);
    pictureBox1.Image = Image.FromStream(mstreem);
    conn.Close();
   conn.Open();
   string sqla = "Update attendance_tbl SET TimeOut = '" + Time + "' , Name ='" + dataGridView1.Rows[i].Cells["Column3"].Value + "'  where stud_id = '" + dataGridView1.Rows[i].Cells["Column1"].Value + "'";
   cmd = new MySqlCommand(sqla, conn);
   cmd.ExecuteNonQuery();
   dataGridView1.Rows[i].Cells["Column7"].Value = DateTime.Now.ToLongTimeString();

这是我的插入代码:

//IF Not In Execute Time-In/Not exist in tbl attendance


 string sqlQu = "select ID,Name,Course,Image from tbl_student_list  where ID= '" + dataGridView1.Rows[i].Cells["Column1"].Value + "'";
 md = new MySqlCommand(sqlQu, conn);
 MySqlDataReader DataReaders = cmd.ExecuteReader();
 DataReaders.Read();
 if (DataReaders.HasRows)
 {
  dataGridView1.Rows[i].Cells["Column3"].Value = DataReaders[1].ToString();
  dataGridView1.Rows[i].Cells["Column4"].Value = DataReaders[2].ToString();
  dataGridView1.Rows[i].Cells["Column2"].Value = DateTime.Now.ToString("yy/MM/dd");
  byte[] images = ((byte[])DataReaders[3]);
  if (images == null)
  {
     pictureBox1.Image = null;
  }
  else
  {
  MemoryStream mstreem = new MemoryStream(images);
  pictureBox1.Image = Image.FromStream(mstreem);
  Purpose f2 = new Purpose();
 if (f2.ShowDialog() == DialogResult.OK)
  {
   dataGridView1.Rows[i].Cells["Column5"].Value = f2.Rad;
  }
  conn.Close();
  conn.Open();
  string sql = "insert into attendance_tbl(stud_id,Date,Name,Course,Purpose,TimeIn)values('" + dataGridView1.Rows[i].Cells["Column1"].Value + "','" + Date + "','" + dataGridView1.Rows[i].Cells["Column3"].Value + "','" + dataGridView1.Rows[i].Cells["Column4"].Value + "','" + dataGridView1.Rows[i].Cells["Column5"].Value + "','" + Time + "')";
     cmd = new MySqlCommand(sql, conn);
     cmd.ExecuteNonQuery();
     dataGridView1.Rows[i].Cells["Column6"].Value = DateTime.Now.ToLongTimeString();

0 个答案:

没有答案