Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Let Join C++ MYSQL library

I’m trying to access "category" table with LEFT JOIN. I need to retrieve the field "name" in this table.

This is my code:

void Product::read(MYSQL *connection)
{
MYSQL_RES *result;
MYSQL_ROW row;

if(mysql_query(connection, "SELECT * FROM product LEFT JOIN category ON product.category=category.category_id"))
    std::cout<<"Query failed!!"<<mysql_error(connection)<<std::endl;
else
    result=mysql_store_result(connection);

if(result->row_count>0)
{
    while(row=mysql_fetch_row(result))
    {

        std::cout<<"Name: "<<row[1]<<" Brand: "<<row[3]<<" Price: "<<row[4]<<" Category: "<<row[5]<<" Amount: "<<row[6]<<std::endl;
    }
}
mysql_free_result(result);
}

And this is the result of the query:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Name: Oneplus Nord 2 5G Brand: Oneplus Price: 299.99 Category: 1 Amount: 3
Name: Acer Swift 3 Brand: Acer Price: 899.99 Category: 2 Amount: 5
Name: Bose SoundLink Revolve Brand: Bose Price: 100.23 Category: 1 Amount: 3

How can I show the name of the category?

>Solution :

You can be more specific about what columns are you selecting and their order. Rather than * you can specify the table_name.column_name (or just column_name if you have no overlaps, or alias_name.column_name if you want to use aliases), so you could try something like:

SELECT product.name, product.brand, product.price, category.name, product.amount FROM product LEFT JOIN category ON product.category=category.category_id

I am assuming how columns are named.

This way the following code will be more predictable, because indices would be based on what you’ve written in select.

std::cout<<"Name: "<<row[1]<<" Brand: "<<row[3]<<" Price: "<<row[4]<<" Category: "<<row[5]<<" Amount: "<<row[6]<<std::endl;
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading