【问题标题】:Retrieve Data from Mysql Database in WebApi To HttpRecquest?在 Web Api 到 Http 请求中从 Mysql 数据库中检索数据?
【发布时间】:2019-02-20 19:00:39
【问题描述】:

我正在尝试从 WebAPI 应用程序中的 MySQL 数据库检索一组数据,并通过来自移动应用程序的 HTTP 请求访问它。因此,我创建了一个 WebApi、一个 RestClient 类和显示数据的类,这是我的代码。

网络 API

[Produces("application/json")]
[Route("api/Blog")]
public class BlogController : Controller
{
    // GET: api/Blog
    [HttpGet]
    public  IEnumerable<string>  Get()
    {

    }

    // GET: api/Blog/5
    [HttpGet("{id}", Name = "GetBlogItems")]
    public string Get(int id)
    {

    }

    // POST: api/Blog
    [HttpPost]
    public void Post([FromBody]  RetrieveDataClass value)
    {
        string sqlstring = "server=; port= ; user id =;Password=;Database=;";
        MySqlConnection conn = new MySqlConnection(sqlstring);
        try
        {
            conn.Open();
        }
        catch (MySqlException ex)
        {
            throw ex;
        }
        string Query = "INSERT INTO test.blogtable (id,Telephone,CreatedSaved,Topic,Summary,Category,Body1,Body2,Body3,Body4)values('" + value.TopicSaved1 + "','" + Value.Telephone + "','" + Value.Created/Saved + "','" + value.TopicSaved1 + "','" +value.SummarySaved1 +"','" +value.CategoriesSaved1 +"','" +value.Body1 +"','" +value.Body2 +"','" +value.Body3 +"','" +value.Body4 +"');";
        MySqlCommand cmd = new MySqlCommand(Query, conn);
        cmd.ExecuteReader();
        conn.Close();

    }

    // PUT: api/Blog/5
    [HttpPut("{id}")]
    public void Put(int id, [FromBody]string value)
    {
    }

    // DELETE: api/ApiWithActions/5
    [HttpDelete("{id}")]
    public void Delete(int id)
    {
    }
}

因此,在我的数据库中,我有三行电话号码为 +233892929292,在过滤器之后我必须得到三行。而且我也会过滤到仅主题和摘要列。

RestClient 类

   public class BlogRestClient<T>
{
    private const string WebServiceUrl = "http://localhost:57645/api/Blog/";

    public async Task<List<T>> GetAsync()
    {

        var httpClient = new HttpClient();

        var json = await httpClient.GetStringAsync(WebServiceUrl);

        var taskModels = JsonConvert.DeserializeObject<List<T>>(json);

        return taskModels;
    }


    public async Task<bool> PostAsync(T t)
    {

        var httpClient = new HttpClient();

        var json = JsonConvert.SerializeObject(t);

        HttpContent httpContent = new StringContent(json);

        httpContent.Headers.ContentType = new MediaTypeHeaderValue("application/json");

        var result = await httpClient.PostAsync(WebServiceUrl, httpContent);

        return result.IsSuccessStatusCode;

    }

    public async Task<bool> PutAsync(int id, T t)
    {
        var httpClient = new HttpClient();

        var json = JsonConvert.SerializeObject(t);

        HttpContent httpContent = new StringContent(json);

        httpContent.Headers.ContentType = new MediaTypeHeaderValue("application/json");

        var result = await httpClient.PutAsync(WebServiceUrl + id, httpContent);

        return result.IsSuccessStatusCode;
    }

    public async Task<bool> DeleteAsync(int id, T t)
    {
        var httpClient = new HttpClient();

        var response = await httpClient.DeleteAsync(WebServiceUrl + id);

        return response.IsSuccessStatusCode;
    }
}

模型数据类

    public class ModelDataClass
    {
         public string Telephone ;
         public string Created/Saved ;
         public string TopicSaved1 ;
         public string SummarySaved1 ;
         public string CategoriesSaved1 ;
         public string Body1 ;
         public string Body2 ;
         public string Body3 ;
         public string Body4 ;


         public ModelDataClass()
         {

         }
    }

ModelDataClass 中字符串的值设置在另一个类中以发布到 MySQL 数据库中。由于这不会导致有问题的问题,因此我没有包含代码。

检索数据类

 public class RetrieveDataClass
    {
         public string Topic ;
         public string Summary ;

         public RetrieveDataClass()
         {
            GetDataEvent();
            AddBlog();
         }

          public void GetDataEvent()
         {
          BlogRestClient<ModelDataClass> restClient = new 
          BlogRestClient<ModelDataClass>();
            await restClient.GetAsync();
         }


      public ObservableCollection<ModelDataClass> BlogItems = new  
      ObservableCollection<ModelDataClass>();

    public void AddBlog()
    {
        BlogListView.ItemsSource = BlogItems;
    }
   }

问题1 如何将数据从 Mysql 检索到通过 REST 客户端类访问的 WebAPI(它适用于移动设备,所以我必须使用 Http 请求)?

问题2 我想为通过 MySQL 数据库检索的每一行创建一个 listView。标题为主题列的数据,副标题为摘要列的数据。

【问题讨论】:

  • 您需要将 MySQL 连接器添加到您的服务器,然后使用 System.DataMySQL.Data 库来检索数据。见-dev.mysql.com/doc/connector-net/en/…
  • @Kami 当然我已经添加了 MysqlConnector 并连接到服务器,那么你如何假设我能够发布数据(如果这就是你的意思)。而且即使我没有连接到服务器,你的回答也不能解决任何问题,谢谢。
  • 你有两个问题,1,如何获取数据。 MySQL 文档很好地概述了如何连接到 MySQL 并执行查询以检索数据。当服务器响应 GET 请求时使用 REST,它不会 POST - 您需要使用相关数据响应 GET 请求。
  • @Kami p 你能用我仍然不明白的代码写出来吗,谢谢。

标签: c# mysql asp.net-web-api xamarin.forms rest-client


【解决方案1】:

您的应用程序是使用Multitier Architecture 模式设计的。因此,您需要确保关注点分离。

Web API 将代表您的表示逻辑层。它将解析客户端的请求,根据需要查询数据并根据需要格式化返回的数据。

然后,RetrieveClient 可以处理数据访问层。它将根据需要管理对数据库的访问、插入、更新、删除。

这里的关键是确保每一层都与另一层对话以执行操作,并且您不会直接访问表示层中的数据库。

因此,

如何检索数据?

在您的数据访问层中:

public class RetrieveDataClass
{
    private IDbConnection connection;

    public RetrieveDataClass(System.Data.IDbConnection connection)
    {
        // Setup class variables
        this.connection = connection;
    }

    /// <summary>
    /// <para>Retrieves the given record from the database</para>
    /// </summary>
    /// <param name="id">The identifier for the record to retrieve</param>
    /// <returns></returns>
    public EventDataModel GetDataEvent(int id)
    {
        EventDataModel data = new EventDataModel();

        string sql = "SELECT id,Telephone,CreatedSaved,Topic,Summary,Category,Body1,Body2,Body3,Body4 WHERE id = @id";
        using (IDbCommand cmd = connection.CreateCommand())
        {
            cmd.CommandText = sql;
            cmd.CommandType = CommandType.Text;

            IDbDataParameter identity = cmd.CreateParameter();
            identity.ParameterName = "@id";
            identity.Value = id;
            identity.DbType = DbType.Int32; // TODO: Change to the matching type for id column

            cmd.Parameters.Add(identity);

            try
            {
                connection.Open();
                using (IDataReader reader = cmd.ExecuteReader())
                {
                    if (reader.Read())
                    {
                        data.id = reader.GetInt32(reader.GetOrdinal("id"));
                        // TODO : assign the rest of the properties to the object
                    }
                    else
                    {
                        // TODO : if method should return null when data is not found
                        data = null;
                    }
                }
                // TODO : Catch db exceptions
            } finally
            {
                // Ensure connection is always closed
                if (connection.State != ConnectionState.Closed) connection.Close();
            }
        }

        // TODO : Decide if you should return null, or empty object if target cannot be found.
        return data;
    }

    // TODO : Insert, Update, Delete methods
}

上面将从数据库中获取一条记录,并将其作为对象返回。您可以改用 ORM 库,例如 EntityFramework 或 NHibernate,但它们有自己的学习曲线。

如何返回数据?

您的客户端将调用 WebAPI,然后从数据访问层查询数据。

[Produces("application/json")]
[Route("api/Blog")]
public class BlogController : Controller
{
    // TODO : Move the connection string to configuration
    string sqlstring = "server=; port= ; user id =;Password=;Database=;";

    // GET: api/Blog
    /// <summary>
    /// <para>Retrieves the given record from the database</para>
    /// </summary>
    /// <param name="id">Identifier for the required record</param>
    /// <returns>JSON object with the data for the requested object</returns>
    [HttpGet]
    public IEnumerable<string> Get(int id)
    {
        IDbConnection dbConnection = System.Data.Common.DbProviderFactories.GetFactory("MySql.Data.MySqlClient");
        RetrieveDataClass dal = new RetrieveDataClass(dbConnection);

        EventDataModel data = dal.GetDataEvent(id);
        if (data != null)
        {
            // Using Newtonsoft library to convert the object to JSON data
            string output = Newtonsoft.Json.JsonConvert.SerializeObject(data);

            // TODO : Not sure if you need IEnumerable<string> as return type
            return new List<string>() { output };
        } else
        {
            // TODO : handle a record not found - usually raises a 404
        }
    }

    // TODO : other methods
}

网上还有很多其他示例说明如何通过 API 访问数据。看看谷歌和评论。想到的几个是

https://docs.microsoft.com/en-us/aspnet/core/tutorials/first-web-api?view=aspnetcore-2.2&tabs=visual-studio

https://docs.microsoft.com/en-us/aspnet/web-api/overview/getting-started-with-aspnet-web-api/tutorial-your-first-web-api

【讨论】:

    【解决方案2】:

    我解决了这个问题。

    WebApi

    [Produces("application/json")]
    [Route("api/Blog")]
    public class BlogController : Controller
    {
    // GET: api/Blog
    [HttpGet]
     public List<BlogViews>  Get()
        {
    
                string sqlstring = "server=; port= ; user id =;Password=;Database=;";
                MySqlConnection conn = new MySqlConnection(sqlstring);
                try
                {
                    conn.Open();
                }
                catch (MySqlException ex)
                {
                    throw ex;
                }
                string Query = "SELECT * FROM test.blogtable where `Telephone` ='Created'";
                MySqlCommand cmd = new MySqlCommand(Query, conn);
                MySqlDataReader MSQLRD = cmd.ExecuteReader();
                List<BlogViews> GetBlogList = new List<BlogViews>();
    
                if (MSQLRD.HasRows)
                {
    
                  while (MSQLRD.Read())
                  {
                    BlogViews BV = new BlogViews();
                    BV.id = (MSQLRD["id"].ToString());
                    BV.DisplayTopic = (MSQLRD["Topic"].ToString());
                    BV.DisplayMain = (MSQLRD["Summary"].ToString());
                    GetBlogList.Add(BV);
                  }
                }
                conn.Close();
            return GetBlogList;
        }
    
    // GET: api/Blog/5
    [HttpGet("{id}", Name = "GetBlogItems")]
    public string Get(int id)
    {
    
    }
    
    // POST: api/Blog
    [HttpPost]
    public void Post([FromBody]  RetrieveDataClass value)
    {
        string sqlstring = "server=; port= ; user id =;Password=;Database=;";
        MySqlConnection conn = new MySqlConnection(sqlstring);
        try
        {
            conn.Open();
        }
        catch (MySqlException ex)
        {
            throw ex;
        }
        string Query = "INSERT INTO test.blogtable (id,Telephone,CreatedSaved,Topic,Summary,Category,Body1,Body2,Body3,Body4)values('" + value.TopicSaved1 + "','" + Value.Telephone + "','" + Value.Created/Saved + "','" + value.TopicSaved1 + "','" +value.SummarySaved1 +"','" +value.CategoriesSaved1 +"','" +value.Body1 +"','" +value.Body2 +"','" +value.Body3 +"','" +value.Body4 +"');";
        MySqlCommand cmd = new MySqlCommand(Query, conn);
        cmd.ExecuteReader();
        conn.Close();
    
    }
    
    // PUT: api/Blog/5
    [HttpPut("{id}")]
    public void Put(int id, [FromBody]string value)
    {
    }
    
    // DELETE: api/ApiWithActions/5
    [HttpDelete("{id}")]
    public void Delete(int id)
    {
    }
    

    }

    RetriveDataClass

       public class RetrieveDataClass
       {
    
         public RetrieveDataClass()
         {
           AddBlog();
         }
      public class BlogViews
        {
            public string id { get; set; }
            public string DisplayTopic { get; set; }
            public string DisplayMain { get; set; }
            public ImageSource BlogImageSource { get; set; }
        }
    
        public List<BlogViews> BlogList1 = new List<BlogViews>();
        public async Task< List<BlogViews>> GetBlogs()
        {
            BlogRestClient<BlogViews> restClient = new BlogRestClient<BlogViews>();
            var BlogV = await restClient.GetAsync();
            return BlogV;
        }
    
        public async void AddBlog()
        {
            BlogList1 = await GetBlogs();
            BlogListView.ItemsSource = BlogList1;
        }
    
    
    }
    

    所以现在我得到一个列表视图,它包含数据库中的每一行,列表视图标题中的每个项目是 DisplayTopic,子标题是 DisplayMain。

    【讨论】:

      猜你喜欢
      • 2019-08-12
      • 2019-06-26
      • 1970-01-01
      • 1970-01-01
      • 2016-09-16
      • 1970-01-01
      • 2017-08-02
      • 2013-03-24
      • 1970-01-01
      相关资源
      最近更新 更多