简体   繁体   中英

Using web service to retrieve more than one database column

I am trying to use a web service to retrieve data for more than one column. The code below works fine :

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;
        }
    }
}

Which just gets the Full name alone, now suppose i want to get for more than just one database column, how do I go about it?

You will want to return a class. Here is a simple class I wrote to hold this data:

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; }
}

Then this method returns that customer object:

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()
                    };
                }
            }
        }
    }
}

This code will return the first customer in the database matching the id_number

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM