2013-04-18 124 views
0

我嘗試使用stringbuilder使過程更簡單,但它顯示錯誤,我不明白問題是否與stringbuilder或代碼語法。解析查詢時發生錯誤。 [令牌行號= 1 ...]

代碼:

 if (dataGridView4.RowCount == 0) 
     { 
      MessageBox.Show("Attendance form is empty"); 
     } 
     else 
     { 
      //string att; 
      int a = dataGridView4.RowCount; 
      string[] s = new string[a]; 
      for (int i = 0; i < a; i++) 
      { 
       if (dataGridView4.Rows[i].Cells[1].Selected) 
       { 
        s[i] = "Present"; 
       } 
       else 
       { 
        s[i] = "Absent"; 
       } 
      } 
      string[] s1 = new string[a]; 
      for (int i = 0; i < a; i++) 
      { 
       s1[i] = dataGridView4.Rows[i].Cells[0].Value.ToString(); 
      } 
      string date = dateTimePicker1.Value.ToString("dd-MM-yyyy"); 
      StringBuilder command = new StringBuilder(); 
      for (int i = 0; i < a; i++) 
      { 
       command.Append("INSERT into Attendance (att_date, emp_code, is_present) values ('" + date + "','" + s1[i] + "','" + s[i] + "')"); 
      } 
      SqlCeConnection conn = new SqlCeConnection(@"Data Source=C:\Users\admin\documents\visual studio 2010\Projects\WindowsFormsApplication1\WindowsFormsApplication1\hotel.sdf"); 
      conn.Open(); 
      SqlCeCommand cmd = new SqlCeCommand(command.ToString(),conn); 
      cmd.ExecuteNonQuery(); 
      MessageBox.Show("Attendance Added"); 

請幫我解決這個錯誤,也如果您有任何建議,使上面的代碼更簡單,請讓我知道。

在此先感謝!

+0

我只注意到,我使用的SQL Server Compact,我收到因爲這個錯誤?我應該使用for循環代替stringbuilder嗎? – 2013-04-18 03:27:47

回答

0

您需要使用的參數,以避免SQL注入攻擊,你也並不需要轉換爲字符串,像你這樣對日期時間參數的..

using (SqlCeConnection con = new SqlCeConnection(strConn)) 
{ 
    con.Open(); 
    using (SqlCeCommand cmd = new SqlCeCommand("insert into Attendance (att_date, emp_code, is_present) values (@att_date, @emp_code, @is_present)", con)) 
    { 
     cmd.Parameters.AddWithValue("@att_date", dateTimePicker1.Value); 
     cmd.Parameters.AddWithValue("@emp_code", emp_codeVal); //s1[i] 
     cmd.Parameters.AddWithValue("@is_present", is_presentVal); //s[i] 
     cmd.CommandType = System.Data.CommandType.Text; 
     cmd.ExecuteNonQuery(); 
    } 
} 

如果有許多記錄,然後插入嘗試使用SqlCeResultSet,您可以查看該鏈接上給出的MSDN示例代碼。

對於每個網格行,你可以做以下

// this is only a sample you need to write for your table 
SqlCeUpdatableRecord rec = rs.CreateRecord(); 

rec.SetInt32(0, 34); 
rec.SetDecimal(1, (decimal)44.66); 
rec.SetString(2, "Sample text"); 

rs.Insert(rec); 
+0

感謝您的幫助。我需要插入多行到數據庫,我必須循環你的代碼,或者有什麼方法可以在你的代碼中使用stringbuilder嗎? – 2013-04-18 03:34:25

+0

在你的代碼中:att_date,emp_code,is_present,基於我的代碼我應該使用@date,s1 [i],s [i]和dateVal,s1 [i] Val,s [i] Val對不對? – 2013-04-18 03:55:21

+0

它應該是'dateTimePicker1.Value,s1 [i],s [i]' – Damith 2013-04-18 04:02:24