      1  #include <iostream>
      2
      3  #include <string>
      4  #include <mysql.h>
      5
      6  using namespace std;
      7
      8  void execute_command(MYSQL* connection, string command)
      9  {
     10     if (mysql_query(connection, command.c_str()) != 0)
     11     {
     12        cout << "Error: " << mysql_error(connection) << "\n";
     13        return;
     14     }
     15
     16     MYSQL_RES* result = mysql_store_result(connection);
     17     if (result == NULL) return;
     18
     19     int rows = mysql_num_rows(result);
     20     int fields = mysql_num_fields(result);
     21     for (int r = 1; r <= rows; r++)
     22     {
     23        MYSQL_ROW row = mysql_fetch_row(result);
     24        for (int f = 0; f < fields; f++)
     25        {
     26           string field(row[f]);
     27           if (f > 0) cout << ",";
     28           cout << field;
     29        }
     30        cout << "\n";
     31     }
     32
     33     mysql_free_result(result);
     34  }
     35
     36  int main()
     37  {
     38     MYSQL* connection = mysql_init(NULL);
     39
     40     if(mysql_real_connect(connection, NULL, NULL, NULL,
     41           "bigcpp", 0, NULL, 0) == NULL)
     42     {
     43        cout << "Error: " << mysql_error(connection) << "\n";
     44        return 1;
     45     }
     46
     47     string line;
     48     bool more = true;
     49     while (getline(cin, line))
     50     {
     51        execute_command(connection, line);
     52     }
     53
     54     mysql_close(connection);
     55     return 0;
     56  }