Last active
December 13, 2016 18:21
-
-
Save pathcl/bc6c750f8eca985dad499d2546a2db19 to your computer and use it in GitHub Desktop.
Simple connector to mysql database
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
/* | |
Does a SQL query defined as 'sql' | |
return 1 if there are no results, else returns 0 | |
In order to compile do this: | |
$ gcc -O2 mysql-api.c -o mysql-api -std=c99 `mysql_config --cflags --libs` | |
You'll need libmysqlclient-dev as for my_global.h and mysql.h | |
*/ | |
#include <my_global.h> | |
#include <mysql.h> | |
#define MAX_QUERY 1024 | |
void finish_with_error(MYSQL *con) | |
{ | |
fprintf(stderr, "%s\n", mysql_error(con)); | |
mysql_close(con); | |
exit(1); | |
} | |
int main(int argc, char *argv[]) | |
{ | |
MYSQL *con = mysql_init(NULL); | |
char *user = argv[1]; | |
char *passwd = argv[2]; | |
char sql[MAX_QUERY]; | |
snprintf(sql, MAX_QUERY, "SELECT * FROM table where user = '%s' and passwd = '%s'", user, passwd); | |
if (con == NULL) | |
{ | |
fprintf(stderr, "mysql_init() failed\n"); | |
exit(1); | |
} | |
if (mysql_real_connect(con, "host", "user", "passwd", | |
"dbname", 0, NULL, 0) == NULL) | |
{ | |
finish_with_error(con); | |
} | |
if (mysql_query(con, sql)) | |
{ | |
finish_with_error(con); | |
} | |
MYSQL_RES *result = mysql_store_result(con); | |
if (result == NULL) | |
{ | |
finish_with_error(con); | |
} | |
if (mysql_num_rows(result) == 0) { | |
finish_with_error(con); | |
} | |
mysql_free_result(result); | |
mysql_close(con); | |
exit(0); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment