C++, Ubuntu, Mysql, query to variable

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • pretzelboy
    New Member
    • Aug 2008
    • 1

    C++, Ubuntu, Mysql, query to variable

    Hi,

    I last wrote software 13years ago in the pascal, dbase, clipper days.
    I have recently built a Ubuntu Box and with C++ (and help from the web) setup a serial barcode reader program using Mysql database tables.

    All works well, and I can do what I need except I am having some trouble with applying an MySQL query result into a defined variable. This would seem like such an easy thing to do.
    The only examples I can find out there are about passing variable parameters into MySQL queries, not the reverse.

    The following code (subset) using "cout" works perfectly, but displays results to the screen.
    I want to to read the query as 3 variables (either text, integer or whatever), store them to be used(compared) as parameters later in the program.

    It is important to note that this table has only 1 record, that is used for config info. Other tables in the database contain the database transactions.
    Also that this code works (displays) the info to the screen, no trouble.

    The question is limited to how to/commands pass the "cout" data to variables instead of screen output.

    Any help is appreciated,


    regards,

    Rod.


    // open the mysql database
    std::string db, server, user, pass;
    mysqlpp::Connec tion conn(false);
    db = "dairy";
    server = "localhost" ;
    user = "root";
    pass = "rod";
    string res = "";
    string port = "";

    if (conn.connect(d b.c_str(), server.c_str(), user.c_str(), pass.c_str())) //connect and get comms parameters
    {
    fputs("Connecte d To SQL Database\n\n",o utput);
    mysqlpp::Query query = conn.query();
    query << "SELECT * FROM control";
    mysqlpp::Result res = query.store();

    if (res)
    {
    char buf(100);
    mysqlpp::Row row;
    mysqlpp::Row::s ize_type i;
    for (i = 0; row =res.at(i); ++i)
    {
    cout << "Printer Port :" << row["Pport"] << "\r\n";
    cout << "Alarm Byte :" << row["Alarmbyte"] << "\r\n";
    cout << "Feeder Byte :" << row["Feederbyte "]<< "\r\n";
    fputs("Configur ation Data Good\n\n",outpu t);
    }
    }

    else
    fputs("Error Getting Configuration Data\n\n",outpu t);
    }
    }
  • weaknessforcats
    Recognized Expert Expert
    • Mar 2007
    • 9214

    #2
    This code:
    Originally posted by pretzelboy
    char buf(100);
    defines one char with a value of 100. Did you mean: char buf[100]?

    You say it works with cout? Then I would use a stringstream intead:
    [code=cpp]
    cout << "Hello" << 123;
    string stream ss;
    ss << "Hello" << 123;
    [/code]

    Now you can use the operator>> on ss to get you your variables:
    [code=cpp]
    string data;
    int value;
    ss >> data >> value;
    [/code]

    Comment

    Working...