微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

MySQL查询中输入的字符串格式不正确

如何解决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,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;
}
它在我在代码标记的位置抛出了错误。任何帮助将非常感激!     

解决方法

        
still_active
的值之一不是有效的整数-也许是空字符串?     ,        为简单起见,我要做的是在执行命令之前,请确保已显示命令文本,以确保它读取了预期的内容。 另外,请注意,如果为NULL,在代码中会发生什么?     ,        如果您正在读取的列值是null或DBNull或空白或不是正确的整数值,则会发生这种情况。     ,        如果still_active始终为TINYINT(1),则使用next:
int projectId = (int)reader[\"still_active\"];
或最好使用
byte
。     ,        考虑在转换前考虑检查字段的值,因为它看起来可能是空字段
reader[\"still_active\"] != DBNull
    ,        最好使用
TryParse
int projectId =0;
Int32.TryParse(Convert.ToInt32(reader[\"still_active\"].ToString(),out projectId); 
    

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。