2011-06-01 52 views
3

在我的代碼中,我在一行中對數據庫進行了多次調用。但是,當我嘗試從數據庫中讀取整數值時,出現以下錯誤:輸入字符串的格式不正確。這是我的代碼:在MySQL查詢中輸入字符串的格式不正確

private int getNumberOfProjectsAssigned() 
{ 
    ArrayList staffProjects = new ArrayList(); 
    int numberOfProjects = 0; 
    try 
    { 
     string strConnection = ConfigurationSettings.AppSettings["ConnectionString"]; 
     MySqlConnection connection = new MySqlConnection(strConnection); 
     MySqlCommand command = connection.CreateCommand(); 
     command.CommandText = "SELECT id_project_pk FROM `test`.`staff_on_project` WHERE id_staff_pk = " + Convert.ToInt32(Session["CurrentUserID"]); 
     //SELECT idusers, first_name, last_name, job_title, code_quality, time_bonus,analysis_of_requirements FROM `test`.`users` WHERE security_level > 1; 
     connection.Open(); 

     MySqlDataReader reader = command.ExecuteReader(); 

     while (reader.Read()) 
     { 
      int projectId = Convert.ToInt32(reader["id_project_pk"].ToString()); 
      staffProjects.Add(projectId); 
     } 
     connection.Close(); 
     foreach (int i in staffProjects) 
     { 
      command.CommandText = "SELECT still_active FROM `test`.`projects` WHERE idprojects = " + i; 
      //SELECT idusers, first_name, last_name, job_title, code_quality, time_bonus,analysis_of_requirements FROM `test`.`users` WHERE security_level > 1; 
      connection.Open(); 

      reader = command.ExecuteReader(); 

      while (reader.Read()) 
      { 
       int projectId = Convert.ToInt32(reader["still_active"].ToString()); // Error Occurs Here 
       if(projectId == 1) 
       { 
        projectsStaffWorksOn.Add(projectId); 
       } 
       numberOfProjects = projectsStaffWorksOn.Count; 
      } 
      connection.Close(); 
     }    
    } 
    catch { } 
    return numberOfProjects; 
} 

它會在我在代碼中標記的位置引發錯誤。任何幫助將非常感激!

+1

調試,看看有什麼價值'reader [「still_active」]' – 2011-06-01 09:20:15

+0

我應該提到still_active不爲null並且是TINYINT(1) – GreeneScreen 2011-06-01 09:21:33

+0

無論如何**不要**使用非泛型ArrayList! – abatishchev 2011-06-01 09:28:55

回答

0

其中still_active的值不是有效整數 - 空字符串可能是?

+0

still_active永遠不爲null。這是一個TINYINT(1) – GreeneScreen 2011-06-01 09:21:06

0

爲了簡單起見,我要做的是在執行命令之前,確保您已經顯示了commandtext以確保它讀取您的預期。

另外,請注意,如果某些內容爲NULL,代碼中會發生什麼?

0

如果您正在讀取的列值爲null或DBNull或空白或者不是適當的整數值,則會發生這種情況。

0

如果STILL_ACTIVE始終是TINYINT(1),然後使用下一個:

int projectId = (int)reader["still_active"]; 

或更好地利用byte

+0

我用它替換它,它給了我以下錯誤:指定的轉換無效。 – GreeneScreen 2011-06-01 09:25:33

+0

@Green:int和byte? – abatishchev 2011-06-01 09:27:08

+0

@綠色:調試它。 'reader [「still_active」]。GetType()。ToString()' – abatishchev 2011-06-01 09:27:24

0

考慮轉換之前檢查該字段的值,因爲它似乎它可能是一個空場

reader["still_active"] != DBNull

-1

它能夠更好地使用TryParse

int projectId =0; 
Int32.TryParse(Convert.ToInt32(reader["still_active"].ToString(),out projectId); 
+0

如果該值肯定是一個'int',那麼不是。 – 2011-06-01 09:48:09