C
26
mysql
Guest on 30th April 2022 11:49:57 PM
#include <iostream.h>
#include <stdio.h>
#include <stdlib.h>
#include <mysql/mysql.h>
int main(int argc, char *argv[]) {
MYSQL *mysql;
MYSQL_RES *result;
//
//
// Connect to the database
mysql = mysql_init(NULL);
if (mysql == NULL) {
fprintf(stderr
,"mysql_init() failed (probably out of memory\n");
}
if ( mysql_real_connect(
mysql, /* pointer to connection handler */
"localhost", /* host to connect to */
"randy", /* user name */
"password", /* password */
"nations", /* database to use */
0, /* port (use default) */
NULL, /* socket (use default) */
0 ) /* flags (none) */
== NULL ) {
fprintf(stderr
,"mysql_real_connect() failed:\nError %u (%s)\n",
mysql_errno(mysql), mysql_error(mysql));
}
//
//
// Run the query
char *query_string = "select name, code, gdp from nations";
if (mysql_query(mysql,query_string))
{
// error
cerr << "There was an sql error\n";
}
else // query succeeded, process any data returned by it
{
result = mysql_store_result(mysql);
if (result == 0) {
// There are no rows
cerr << "There were no rows\n";
}
}
//
//
// Get the answers
MYSQL_ROW row;
unsigned int num_fields;
unsigned int i;
num_fields = mysql_num_fields(result);
while ((row = mysql_fetch_row(result)))
{
unsigned long *lengths;
lengths = mysql_fetch_lengths(result);
for(i = 0; i < num_fields; i++)
{
if (row[i] != 0)
cout << " " << row[i];
else
cout << " NULL";
}
cout << endl;
}
//
//
// Close the connection
mysql_close(mysql);
}