Created
November 28, 2018 04:18
-
-
Save tim-cotten/678b7b7d1d6f3ec02ebed0ffdc5813da to your computer and use it in GitHub Desktop.
An example of connecting to a MySQL database in C using a config text file
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <mysql.h> | |
#include <my_global.h> | |
// Note: TRUE and FALSE will always be defined by the MySQL headers | |
#define MYSQL_CONF_NUM 4 | |
#define MYSQL_CONF_HOSTNAME 0 | |
#define MYSQL_CONF_DATABASE 1 | |
#define MYSQL_CONF_USERNAME 2 | |
#define MYSQL_CONF_PASSWORD 3 | |
/** | |
* Load a MySQL config text file consisting of four separate lines: | |
* - hostname | |
* - database name | |
* - username | |
* - password | |
* | |
* assumes macros for TRUE = 1, FALSE = 0 | |
* returns (int) success | |
*/ | |
int get_mysql_conf(char *conf[]) | |
{ | |
// Load the config file | |
FILE *fp = fopen("CONFIG_FILE_PATH_GOES_HERE", "r"); | |
if (!fp) { | |
return FALSE; | |
} | |
// Read each required line, error if empty | |
char buffer[1024]; | |
for (int i = 0; i < MYSQL_CONF_NUM; ++i) { | |
if (fgets(buffer, sizeof(buffer), fp) == NULL) { | |
return FALSE; | |
} | |
strtok(buffer, "\n"); | |
strtok(buffer, "\r"); | |
conf[i] = malloc(sizeof(char) * strlen(buffer) + 1); | |
if (conf[i] == NULL) { | |
return FALSE; | |
} | |
strcpy(conf[i], buffer); | |
} | |
fclose(fp); | |
return TRUE; | |
} | |
// Open a database connection | |
printf("MySQL client version: %s\n", mysql_get_client_info()); | |
MYSQL *conn = mysql_init(NULL); | |
if (conn == NULL) { | |
printf("ERROR: Could not create database connection\n"); | |
return 1; | |
} | |
// Load the config file | |
char *conf[MYSQL_CONF_NUM]; | |
if (!get_mysql_conf(conf)) { | |
printf("ERROR: Could not load database configuration file\n"); | |
return 1; | |
} | |
// Connect to the target database | |
if (mysql_real_connect(conn, conf[MYSQL_CONF_HOSTNAME], conf[MYSQL_CONF_USERNAME], conf[MYSQL_CONF_PASSWORD], conf[MYSQL_CONF_DATABASE], 0, NULL, 0) == NULL) { | |
printf("ERROR: Could not connect to the target database\n"); | |
return 1; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment