C# MySQL Update

C#/C# SQL 2016. 8. 22. 06:42
728x90

dataGridView 에서 작업한 것을 수정한 결과를 Update 하는 코드이다.

여러개의 자료를 수정한 경우 신규 수정인지 기존 자료 수정인지 검사하는 로직이 구현되어 있다.


private void btnSave_Click(object sender, EventArgs e)
{
    int UpdateCnt = 0; int ModifiedCnt = 0;

    myConn = new MySqlConnection(GetConnectionString());
    if (myConn.State == ConnectionState.Closed)
    {
        myConn.Open();
        DBstatus.Text = "ON";
    }

    try
    {
        foreach (DataGridViewRow row in this.dataGridView1.Rows)
        {
            string uid = row.Cells["uid"].Value.ToString();
            string str1 = row.Cells["content"].Value.ToString();
            string str2 = row.Cells["code"].Value.ToString();
            string d_regis = DateTime.Now.ToString("yyyyMMddHHmmss");

            if (str1 == null || str1.Equals("")) { continue; }  // 수정이 없을 경우
            else if (str2 == Convert.ToString(0))  // 신규 수정
            {
                string strqry = "UPDATE data SET code='" + f2.getCode + "', content='" + str1.Trim() + "', d_modify='" + d_regis + "' Where uid =" + uid;
                MySqlCommand cmd = new MySqlCommand(strqry, myConn);
                cmd.ExecuteNonQuery();
                UpdateCnt++;
                cmd.Dispose();
            }
            else if (str2 == Convert.ToString(f2.getCode))  // 등록자와 동일한 것만 수정여부 검사
            {                       
                string strqry = string.Format("SELECT count(*) FROM data WHERE uid='{0}' and content='{1}'",uid, str1);
                MySqlCommand cmd = new MySqlCommand(strqry, myConn);
                cmd.CommandType = CommandType.Text;
                int RowCount = Convert.ToInt32(cmd.ExecuteScalar());
                cmd.Dispose();
                if (RowCount == 0)
                {
                    strqry = "UPDATE data SET code='" + f2.getCode + "', content='" + str1.Trim() + "', d_modify='" + d_regis + "' Where uid =" + uid;
                    MySqlCommand cmb = new MySqlCommand(strqry, myConn);
                    cmb.ExecuteNonQuery();
                    ModifiedCnt++;
                    cmb.Dispose();
                }
            }
        }
        GetAllItems();  //Refresh grid
        MessageBox.Show(UpdateCnt + "건 Updated " + ModifiedCnt + "건 수정 되었습니다...");
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.Message);
    }
    finally
    {
        if (myConn.State == ConnectionState.Open)
        {
            myConn.Close();
            DBstatus.Text = "OFF";
        }
    }

}



728x90
블로그 이미지

Link2Me

,