Home > Software engineering >  how to select specified row in mysql with asp.net core
how to select specified row in mysql with asp.net core

Time:09-16

I want to select a row in the table with id. How can I do it with asp.net core? Can anyone help me?

MyCode

 [HttpGet("{id}")]
    public JsonResult Get(int id)
    {
        string query = @"
                    select id,firstname,lastname from 
                    udemydb.users where id=@UsersId
        ";

        DataTable table = new DataTable();
        string sqlDataSource = _configuration.GetConnectionString("UsersAppCon");
        MySqlDataReader myReader;
        using (MySqlConnection mycon = new MySqlConnection(sqlDataSource))
        {
            mycon.Open();
            using (MySqlCommand myCommand = new MySqlCommand(query, mycon))
            {
                myReader = myCommand.ExecuteReader();
                table.Load(myReader);

                myReader.Close();
                mycon.Close();
            }
        }

        return new JsonResult(table);
    }

Where I did go wrong in the above code?

CodePudding user response:

you have to add a cmd parameter

  using (MySqlCommand myCommand = new MySqlCommand(query, mycon))
  {
     myCommand.Parameters.AddWithValue("@UsersId", id);
    myReader = myCommand.ExecuteReader();
    ......
  • Related