john mondego
john mondego

Reputation: 189

C++ nested loop using %s

(Totally new to C++. Coming from python.)

Vector of names: namelist, vector of stats: statlist. Each name is a mysql table and each stat is a column in that table.

for (unsigned int i = 0; i < namelist.size(); i++)
{
    for (unsigned int j = 30; j < statlist.size(); j++)
    {
        string selectcolumn = "SELECT %s FROM %s.%s", statlist, statlist, namelist;
        const char* c = selectcolumn.c_str();
        qstate = mysql_query(conn, c);
    }
}

(I don't expect people to do this for me I just need some guidance/advice. ANY help is really appreciated!)

Each column row will be ranked by percentile then split into groups by 10 and put into another table.

  1. How do I correctly associate variables to %s string in the loop here?
  2. Do I need to dynamically generate a vector for each column as I select it?
  3. Once I select a table column do I need to use a while loop?

Upvotes: 1

Views: 146

Answers (3)

user10957435
user10957435

Reputation:

  1. How do I correctly associate variables to %s string in the loop here?

If you're looking for a direct equivalent to what you are doing in Python, you might be looking for printf().

However, I would probably do what others have suggested, and simply concatenate the strings directly:

string selectcolumn = "SELECT " + statlist " FROM " + statlist "." + namelist;

That said, I would be doing you a disservice if I didn't warn you about SQL Injection, which you are open to by simply inserting this data into your query. There are lots of ways to prevent this, though I'm not sure how this applies to C++, as you seem to be using some 3rd party SQL library. However, I would imagine the principle is the same.

2.Do I need to dynamically generate a vector for each column as I select it? 3.Once I select a table column do I need to use a while loop?

This really depends on what you're using to interface with your SQL server, and how the data is given back to you. The details of this are unclear, to it's impossible to answer that part properly.

Upvotes: 2

RoQuOTriX
RoQuOTriX

Reputation: 3001

If we can't see what types statlist and namelist are, we can only assume they are std::vector's. I don't really know if this is the "logic" you want, but you could concatenate the string like this:

for (unsigned int i = 0; i < namelist.size(); i++)
{
    for (unsigned int j = 30; j < statlist.size(); j++)
    {
        std::string selectcolumn = "SELECT " + statlist[j] +"FROM " + statlist[j] + "." + namelist[i];
        const char* c = selectcolumn.c_str();
        qstate = mysql_query(conn, c);
    }
}

Upvotes: 1

mathmaniac88
mathmaniac88

Reputation: 640

Given that statlist and namelist are strings too, you can use the concatenation operator ("+" in C++)

For example, in this case, you would do:

"SELECT " + statlist + " FROM " + namelist + "." + statlist

Upvotes: 1

Related Questions