Last active
August 29, 2015 14:12
-
-
Save bgunebakan/0762fdc087118700fdc6 to your computer and use it in GitHub Desktop.
mysql c api test code
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
/* Simple C program that connects to MySQL Database server | |
* | |
* compile with $(mysql_config --cflags) mysql-c-api.c $(mysql_config --libs) | |
*dependencies: libmysql-dev mysql-client | |
*/ | |
#include <mysql.h> | |
#include <stdio.h> | |
#include <string.h> | |
#include <time.h> | |
main() { | |
//date and time variables | |
time_t t = time(NULL); | |
struct tm tm = *localtime(&t); | |
char currentDate[10]; | |
char currentTime[8]; | |
MYSQL *conn; | |
MYSQL_RES *res; | |
MYSQL_ROW row; | |
char *server = "localhost"; | |
char *user = "testuser"; | |
char *password = "123456"; /* set me first */ | |
char *database = "test"; | |
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)); | |
//exit(1); | |
} | |
printf("build query\n"); | |
sprintf(currentDate, "%04d.%02d.%02d",tm.tm_year + 1900, tm.tm_mon+1, tm.tm_mday); | |
sprintf(currentTime, "%02d:%02d:%02d", tm.tm_hour, tm.tm_min, tm.tm_sec); | |
char *card_no = "222"; | |
char st[250]; //= "INSERT INTO door_control(id,card_no,date,time) VALUES(4, '%s','%s','%s')"; | |
sprintf(st,"INSERT INTO door_control(id,card_no,date,time) VALUES(7, '%s','%s','%s')",card_no,currentDate,currentTime); | |
int st_len = strlen(st); | |
//char query[st_l]; | |
//int len = snprintf(query,st_len + strlen(card_no) , st, chunk); | |
printf("sql query:\n%s\n----------\n",st); | |
int len = strlen(st); | |
if (mysql_real_query(conn, st, len)){ | |
//finish_with_error(conn); | |
fprintf(stderr, "%s\n", mysql_error(conn)); | |
} | |
/* send SQL query */ | |
if (mysql_query(conn, "SELECT * from door_control")) { //show tables | |
fprintf(stderr, "%s\n", mysql_error(conn)); | |
//exit(1); | |
} | |
res = mysql_use_result(conn); | |
/* output table name */ | |
printf("door control table data:\n"); | |
while ((row = mysql_fetch_row(res)) != NULL){ | |
printf("%s %s %s %s \n", row[0],row[1],row[2],row[3]); | |
} | |
/* close connection */ | |
mysql_free_result(res); | |
mysql_close(conn); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment