我正在尝试从WebAPI应用程序中的MySQL数据库检索一组数据,并通过来自移动应用程序的HTTP请求来访问它。因此,我创建了一个WebApi,一个RestClient类以及用于显示数据的类,这就是我的代码。
Web 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;
}
}
ModelData类
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数据库中。由于这不会引起问题,因此我没有包含代码。
RetrieveDataClass
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。标题是主题列中的数据,子标题是摘要列中的数据。
答案 0 :(得分:0)
您的应用程序是使用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访问数据。看看谷歌和审查。想到的是
答案 1 :(得分:0)
我解决了这个问题。
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;
}
}
所以现在我得到一个listview,它包含数据库中的每一行,并且listview标题中的每个项目都是DisplayTopic,子标题是DisplayMain。