使用Web服务检索多个数据库列

时间:2018-08-17 15:33:42

标签: c# sql-server web-services

我正在尝试使用Web服务来检索多于一列的数据。下面的代码可以正常工作:

public string GetCustomerNameWithIDNumber(string id_number)
{
    string fullname ="";
    string id_type = "";
    string id_number = "";
    string dob = "";

    using (SqlConnection cn = new SqlConnection(constring))
    {
        cn.Open();
        string q = "select fullname, id_type, id_number, date_ofbirth from account_info where id_number = @id_number";

        using (SqlCommand cmd = new SqlCommand(q, cn))
        {
            cmd.Parameters.AddWithValue("@id_number", id_number);

            using (SqlDataReader rd = cmd.ExecuteReader())
            {
                while (rd.Read())
                {
                    fullname = rd["fullname"].ToString();
                    id_type = rd["id_type"].ToString();
                    id_number = rd["id_number"].ToString();
                    dob = rd["date_ofbirth"].ToString();
                    bvn2 = rd["bvn"].ToString();
                }
            }

            return fullname;
        }
    }
}

仅获得全名的人,现在假设我想获得的不只是一个数据库列,我该如何处理?

1 个答案:

答案 0 :(得分:1)

您将要返回一个课程。这是我编写的用于保存此数据的简单类:

class Customer {
    public string FullName { get; set; }
    public string IdType { get; set; }
    public string IdNumber { get; set; }
    public string DateOfBirth { get; set; }
    public string Bvn { get; set; }
}

然后此方法返回该客户对象:

public Customer GetCustomerNameWithIDNumber(string id_number) {
    using (SqlConnection cn = new SqlConnection(constring)) {
        cn.Open();
        string q = "select fullname,id_type,id_number,date_ofbirth from account_info where id_number =@id_number";

        using (SqlCommand cmd = new SqlCommand(q, cn)) {
            cmd.Parameters.AddWithValue("@id_number", id_number);
            using (SqlDataReader rd = cmd.ExecuteReader()) {
                while (rd.Read()) {
                    return new Customer {
                        FullName = rd["fullname"].ToString(),
                        IdType= rd["id_type"].ToString(),
                        IdNumber = rd["id_number"].ToString(),
                        DateOfBirth = rd["date_ofbirth"].ToString(),
                        Bvn = rd["bvn"].ToString()
                    };
                }
            }
        }
    }
}

此代码将返回数据库中与id_number匹配的第一个客户