예방

2013-11-02 4 views
0
 private void Save_Click(object sender, EventArgs e) 
    { 
     string strconn = @"Server=.\SQLEXPRESS;initial catalog=PharmacyV2;integrated security=true;"; 
     SqlConnection conn = new SqlConnection(strconn); 
     //SqlCommand cmd = new SqlCommand(); 
     DataSet ds = new DataSet(); 
     conn.Open(); 
     SqlDataAdapter da = new SqlDataAdapter("select * from Units",conn); 
     da.Fill(ds, "Units"); 
     bool found = false; 
     for (int i = 0; i < dataGridView1.Rows.Count; i++) 
     { 

      for (int j = 0; j < ds.Tables["Units"].Rows.Count; j++) 
      { 


       if (ds.Tables["Units"].Rows[j][0].ToString() == dataGridView1.Rows[i].Cells[0].Value.ToString()) 
       { 
        found = true; 
        break; 
       } 

      } 

      if (found==false) 
      { 

       SqlCommand cmd; 
       cmd = new SqlCommand("insert into Units (Unit_name) values (@name)", conn); 
       cmd.Parameters.AddWithValue("@name", dataGridView1.Rows[i].Cells[0].Value.ToString()); 
       cmd.ExecuteNonQuery(); 
       MessageBox.Show("تمت الاضافه"); 


      } 
     } 
     conn.Close(); 

    } 

내 프로그램이 데이터베이스 의 중복을 방지하기 위해 데이터베이스에서 UINT 테이블의 모든 요소에있는 DataGridView에서 각 요소를 비교 데이터베이스에 항목을 중복 statement 프로그램이 데이터베이스에 데이터를 삽입하지 않는 이유는 무엇입니까? 는예방

+0

오류 또는 예외 메시지가 있습니까? –

+0

'dataGridView1.Rows.Count'의 값은 무엇입니까? 중단 점을 넣은 다음 확인하십시오 – sll

+0

그리고 SqlConnection 객체를 삭제하십시오. 즉, (SqlConnection conn = new SqlConnection (strconn)) {0125.BuildByyyyyyyy} – Stefan

답변

0

루프에 대한 첫 번째 내부에 허위로 발견 변수를 초기화 (삽입 문을 구현하지 않음) :

found = false;

을 그래서이 모든 반복에 대해 초기 상태로 설정됩니다. 그렇지 않으면 true로 설정되면 항상 true가됩니다. 그 이유는 insert 문이 실행되지 않는 이유입니다. 데이터베이스를 요청에 대한 항목이 존재하는지 확인하는 방법

for (int i = 0; i < dataGridView1.Rows.Count; i++) 
    { 
     found = false; 

     for (int j = 0; j < ds.Tables["Units"].Rows.Count; j++) 
     { 


      if (ds.Tables["Units"].Rows[j][0].ToString() == dataGridView1.Rows[i].Cells[0].Value.ToString()) 
      { 
       found = true; 
       break; 
      } 

     } 

     if (found==false) 
     { 

      SqlCommand cmd; 
      cmd = new SqlCommand("insert into Units (Unit_name) values (@name)", conn); 
      cmd.Parameters.AddWithValue("@name", dataGridView1.Rows[i].Cells[0].Value.ToString()); 
      cmd.ExecuteNonQuery(); 
      MessageBox.Show("تمت الاضافه"); 


     } 
    } 
0

:

그래서 루프처럼 보여야?

var unitName = dataGridView1.Rows[i].Cells[0].Value.ToString(); 
var command = new SqlCommand("SELECT COUNT(*) FROM Units WHERE Unit_name = @name", connection); 
command.Parameters.AddWithValue("@name", unitName); 

int result = (int)command.ExectureScalar(); 

if(result == 0) // no entry 
{ 
    //Insert. 
}