/* Full article at http://marksitblog.blogspot.com */
#include <stdio.h>
#include <mysql.h>
int main()
{
MYSQL *connection;
MYSQL_RES *resource;
MYSQL_ROW result;
char *servername= "localhost";
char *user= "root";
char *password= "";
char *database= "world";
char *socket= "/opt/lampp/var/mysql/mysql.sock";
char *hostinfo;
char *serverinfo;
int protoinfo;
/* Intitialize connection to database, and MYSQL structure. */
connection = mysql_init(NULL);
/* Connect to database */
if(!mysql_real_connect(connection, servername, user,
password, database, 0, socket, 0)) {
printf("%s\n", mysql_error(connection));
}
/* Get host info */
hostinfo = mysql_get_host_info(connection);
/* Get server info */
serverinfo = mysql_get_server_info(connection);
/* Get protocol info */
protoinfo = mysql_get_proto_info(connection);
/* Output get info */
printf("Host: %s\n", hostinfo);
printf("Server: %s\n", serverinfo);
printf("Protocol: %d\n", protoinfo);
/* Execute our SHOW DATABASES statement */
mysql_query(connection, "SHOW DATABASES");
/* Resource structure with the rows of data from SHOW DATABASES */
resource = mysql_use_result(connection);
printf("Databases:\n\n");
/* Fetch & print each row */
while((result = mysql_fetch_row(resource))) {
printf("%s\n", result[0]);
}
/* SELECT more data from world database. */
mysql_query(connection, "SELECT Name, Population FROM City ORDER BY Name");
/* Resource struct with rows of returned data. */
resource = mysql_use_result(connection);
printf("\n\nCities and populations in City table:\n\n");
/* Print out all our cities with populations */
while((result = mysql_fetch_row(resource))) {
printf("%s %s\n",result[0], result[1]);
}
/* UPDATE San Diego population */
mysql_query(connection, \
"UPDATE City SET Population=\"1300000\" WHERE ID=\"3799\"");
printf("%ld Row(s) Updated!\n", (long) mysql_affected_rows(connection));
/* SELECT newly inserted record. */
mysql_query(connection, \
"SELECT Name, Population FROM City WHERE Name = 'San Diego'");
/* Resource struct with rows of returned data. */
resource = mysql_use_result(connection);
/* Fetch single result */
result = mysql_fetch_row(resource);
/* Display San Diego's new population */
printf("%s %s\n",result[0], result[1]);
/* Free memory used by resource */
mysql_free_result(resource);
/* Closes connection to database, frees memory used by connection. */
mysql_close(connection);
/* Frees up other memory used by the libmysqlclient. */
mysql_library_end();
return 0;
}