使用RESTful Web服务从MySql数据库中检索数据

时间:2016-07-28 16:47:49

标签: c# php mysql xamarin.forms

我正在使用Xamarin.forms进行跨平台应用,我需要从MySql Server检索数据。通过我的研究,我发现使用MySqlClient库是不安全的,所以我在我的数据库和应用程序之间使用Web服务层进行搜索。

此代码对MySql数据库进行查询,在数组中输出结果并以JSON编码回显它们。这是PHP代码:

<?php
$servername = "adress";
$username = "client";
$password = "";
$dbname = "dnName";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

$sql = "SELECT text1, text2 FROM tblTable";
$result = $conn->query($sql);

if ($result->num_rows > 0) {
    $items = array();
    // output data of each row
    while($row = $result->fetch_assoc()) {
        $item = array("Texte1" => $row['text1'],
                                         "Texte2" => $row['text2']);
        array_push($items, $item);
    }
    echo json_encode($items);
} else {
    echo "0 results";
}
$conn->close();
?> 

此代码调用PHP文件,获取响应并将其转换为项目列表。这是C#代码:

using System.Net.Http;
using Newtonsoft.Json;
//....

    private Uri uri;
    private HttpClient client;
    private List<Items> item;

    public async Task<List<Items>> ReadData()
    {
        client = new HttpClient();
        uri = new Uri("http://adress/getdata.php");

        var response = await client.GetAsync(uri);
        if (response.IsSuccessStatusCode)
        {
            var content = await response.Content.ReadAsStringAsync();
            item = JsonConvert.DeserializeObject<List<Items>>(content);
        }
        return item;
    }

    public class Items
    {
        public string text1 { get; set;}
        public string text2 { get; set;}
    }

现在,ReadData方法的返回类型是List<Items>但是如何在List<string>或简单字符串中返回它们?

1 个答案:

答案 0 :(得分:0)

Linq的一些选项(不要忘记包含“使用System.Linq;”)。我更喜欢使用选项2

  1. 返回匿名类型:

    var mylist = item.Where(x => x != null)
                        .Select(x => new { x.text1, x.text2 }).ToList();
    
  2. 返回字符串列表列表:

    List<List<string>> mylist = listItems.Where(x => x != null)
                              .Select(x => new List<string>{ x.text1, x.text2}).ToList();