I'm new to C# and.Net programmes, but I'm attempting to create a Web API that gets data from a MySql database and displays it in JSON format when you hit that endpoint.
I'm working with MySql.Data.MySqlClient for this and use with Newtonsoft.JSON to serialize the result format in JSON format
My code
[Route("api/[controller]")]
[ApiController]
public class TestController : ControllerBase
{
MySqlConnection conn = new MySqlConnection(@"server=localhost;port=3306;database=mysql;username=root;password=[PASSWORD];");
[HttpGet]
public string Get()
{
MySqlCommand query = conn.CreateCommand();
query.CommandText = "SELECT * FROM engine_cost LIMIT 100";
try
{
conn.Open();
}
catch (MySqlException ex)
{
throw ex;
}
MySqlDataReader fetch_query = query.ExecuteReader();
while (fetch_query.Read())
{
return fetch_query.ToString(); // Result: "MySql.Data.MySqlClient.MySqlDataReader"
}
return "yay"; // Return JSON with Database values
}
}
The code is not the best but how to manage this?