Saturday, 24 August 2013

ANSI C Function to Update Database

ANSI C Function to Update Database

I'm using a ANSI C snippet that successfully connects to a MySQL database
and executes a query. As i can successfully call to a function in my
program that sends any query I want to the database, then I have some
pretty powerful options available to me.
One option I want to use is the ability to INSERT INTO one variable to a
selected table in one or more columns. That way I can use a simple
function to pass data to my database as opposed to duplicating the code
for every variable I want to store. I.e.: I want to reduce the amount of
work and time by creating a function where I can easy update my database.
My program is actually a game. It stores it's data in flat files. I'm
making a big switch where I will now store my data in a local database.
There are a lot of stats for players that are normally stored in a flat
file. Things like Name, Sex, Class, Race, Level and etc.
Example of how the old way writes this player data.
fprintf (fp, "Name %s~\n", player->name);
With a new function, I want to effectively pass 'player->name' to my query
that in result, stores to the database. As relational databases store data
in various tables and columns. I need to also have options to set a
destination table and destination column.
One solution I had was with concatenation. At least that's how it seems to
be done in PHP. This is where you concatenate SQL query with variables.
But unfortunately, I don't know how to effectively concatenate strings
together where I can pass "player->name" into my query of:
INSERT INTO test_table VALUES ('', '');
That said, here is my MySQL snippet that does work magically:
#include <mysql.h>
#include <stdio.h>
void db_update(const char * query)
{
MYSQL *conn;
MYSQL_RES *res;
MYSQL_ROW row;
char *server = "localhost";
char *user = "root";
char *password = "PASSWORD"; /* set me first */
char *database = "DATABASE";
conn = mysql_init(NULL);
/* Connect to database */
if (!mysql_real_connect(conn, server,
user, password, database, 0, NULL, 0)) {
fprintf(stderr, "%s\n", mysql_error(conn));
return;
}
/* send SQL query */
if (mysql_query(conn, query)) {
fprintf(stderr, "%s\n", mysql_error(conn));
return;
}
/* close connection */
mysql_free_result(res);
mysql_close(conn);
}
Compiling
mysql: MySQL client programs and shared library mysqlclient: Backlevel
MySQL shared libraries (old libs) mysql-devel: Files for development of
MySQL applications (a must have) mysql-server: Mysql server itself gcc,
make and other development libs: GNU C compiler
Pass --libs option - Libraries and options required to link with the MySQL
client library.
mysql_config --libs
mysql_config --cflags
Example: gcc -o output-file $(mysql_config --cflags) database.c
$(mysql_config --libs)
Final Note
This may be a bit too complex for Stackoverflow, but any leads to how I
can make this happen would be great. I want to learn as much as I can.

No comments:

Post a Comment