0

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?

5
  • What error or problem are you seeing? Commented Sep 14, 2021 at 14:54
  • I can't select a specific row in the table. Commented Sep 14, 2021 at 14:57
  • is there an error or do you just not get any data? Does the query work on its own without c#? Commented Sep 14, 2021 at 15:12
  • For ExecuteReader, have you tried checking if it HasRows? Commented Sep 14, 2021 at 15:14
  • Side note: you're not using the id parameter in the query. Commented Sep 14, 2021 at 15:46

1 Answer 1

2

you have to add a cmd parameter

  using (MySqlCommand myCommand = new MySqlCommand(query, mycon))
  {
     myCommand.Parameters.AddWithValue("@UsersId", id);
    myReader = myCommand.ExecuteReader();
    ......
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.