better code with cout

I am calling a SELECT from Mysql and the row is having three fields. Just for test, the third field has some NULL values. As soon as cout sees a NULL, it quits, not completing the reading of the rows. If I have 4 rows and the second one has a NULL, it stops right there. I have a solution, but I find it awkward. Can somebody look at the code and suggest a better solution, because if I have a row with 20 fields, it makes a lot of if-else to test each one of them to check for NULL. Here is the code:


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
  if(conn)
  	{
  		int qstate = mysql_query(conn,"SELECT numeroreference,nom,age FROM test");

  		if(!qstate)
  		{
  		res = mysql_store_result(conn);

  		while(row = mysql_fetch_row(res))
  		{

        std::string s;
        s.append(row[0]);
        s.append(" ");
        s.append(row[1]);

        if(row[2] != NULL)
            {
            s.append(" ");
            s.append(row[2]);
            cout << s << endl << endl;
            }
        else
            {
            cout << s << endl << endl;
            }

  		}
  		}

Last edited on
The first thing would be to show decently formatted code.
If you want your code to look good everywhere, then you absolutely have to be consistent in how you indent code. Mixing spaces and tabs always produces a mess at some point.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
  if (conn) {
    int qstate = mysql_query(conn, "SELECT numeroreference,nom,age FROM test");
    if (!qstate) {
      res = mysql_store_result(conn);
      while (row = mysql_fetch_row(res)) {
        std::string s;
        s.append(row[0]);
        s.append(" ");
        s.append(row[1]);
        if (row[2] != NULL) {
          s.append(" ");
          s.append(row[2]);
          cout << s << endl << endl;
        } else {
          cout << s << endl << endl;
        }
      }
    }
  }


> because if I have a row with 20 fields, it makes a lot of if-else to test each one of them to check for NULL.
So is there some mysql_ function that tells you how many fields are in a row?

Like this?
https://dev.mysql.com/doc/c-api/5.6/en/mysql-field-count.html

You have a row, and the result of mysql_field_count, you can write yourself a nice little for loop.
Topic archived. No new replies allowed.