从数据库获取数据时出错

时间:2017-04-18 06:32:40

标签: c#

这是获取百分比的代码,但返回一个空数组。不知道如何解决它

List<Employee> employees = new List<Employee>();
SqlConnection conn = new SqlConnection("data source=***.***.***.***;initial catalog=***;persist security info=True;user id=***;password=***;MultipleActiveResultSets=True;App=EntityFramework");

using (conn)
{
    SqlCommand cmd = new SqlCommand("SELECT (CAST(Availability as int)/CAST(Functionality as int))*100 from Vu_EquipmentInfo where Vu_EquipmentInfo.MonitoringDate like " + year + "-" + month, conn);
    SqlDataReader reader = cmd.ExecuteReader();

    while(reader.Read())
    {
        Employee employee = new Employee();
        employee.Sanctioned_Post = Convert.ToString(reader\["Availability"\]);
        // employee.Fill_Post = Convert.ToChar(reader\["District"\]);
        employees.Add(employee);
    }

    JavaScriptSerializer js = new JavaScriptSerializer();
    Context.Response.Write(js.Serialize(employees));
}

enter image description here

2 个答案:

答案 0 :(得分:0)

所以,首先 - 打开连接。

接下来,将select修改为select 'exp' as Availability

List<Employee> employees = new List<Employee>();
            SqlConnection conn = new SqlConnection("data source=***.***.***.***;initial catalog=***;persist security info=True;user id=***;password=***;MultipleActiveResultSets=True;App=EntityFramework");
            await conn.OpenAsync();
            using (conn)
            {
                SqlCommand cmd = new SqlCommand("SELECT (CAST(Availability as int)/CAST(Functionality as int))*100 as Availability from Vu_EquipmentInfo where Vu_EquipmentInfo.MonitoringDate like " + year + "-" + month, conn);
                SqlDataReader reader = await cmd.ExecuteReaderAsync();
                while (await reader.ReadAsync())
                {
                    Employee employee = new Employee();
                    employee.Sanctioned_Post = Convert.ToString(reader["Availability"]);
                    employees.Add(employee);
                }
                JavaScriptSerializer js = new JavaScriptSerializer();
                await Context.Response.WriteAsync(js.Serialize(employees));
            }

答案 1 :(得分:0)

如果MonitoringDate是一个字符串,你应该比较它......在连接字符串后考虑你的where子句(年和月的假设值)

Vu_EquipmentInfo.MonitoringDate like 2017-12

也许你想要这样的东西

Vu_EquipmentInfo.MonitoringDate like '2017-12%'

但问题的水平还很缺乏。