By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
426,060 Members | 1,878 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 426,060 IT Pros & Developers. It's quick & easy.

C++, Ubuntu, Mysql, query to variable

P: 1

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,



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

if (conn.connect(db.c_str(), server.c_str(), user.c_str(), pass.c_str())) //connect and get comms parameters
fputs("Connected To SQL Database\n\n",output);
mysqlpp::Query query = conn.query();
query << "SELECT * FROM control";
mysqlpp::Result res =;

if (res)
char buf(100);
mysqlpp::Row row;
mysqlpp::Row::size_type i;
for (i = 0; row; ++i)
cout << "Printer Port :" << row["Pport"] << "\r\n";
cout << "Alarm Byte :" << row["Alarmbyte"] << "\r\n";
cout << "Feeder Byte :" << row["Feederbyte"]<< "\r\n";
fputs("Configuration Data Good\n\n",output);

fputs("Error Getting Configuration Data\n\n",output);
Sep 20 '08 #1
Share this Question
Share on Google+
1 Reply

Expert Mod 5K+
P: 9,197
This code:
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:
Expand|Select|Wrap|Line Numbers
  1. cout << "Hello" << 123;
  2. string stream ss;
  3. ss << "Hello" << 123;
Now you can use the operator>> on ss to get you your variables:
Expand|Select|Wrap|Line Numbers
  1. string data;
  2. int value;
  3. ss >> data >> value;
Sep 20 '08 #2

Post your reply

Sign in to post your reply or Sign up for a free account.