Databases InterBase (28) MS-SQL (5) mysql (33) Oracle (1)
Exchange Links About this site Links to us
|
Stub to connect from a C program to mysql
This article has not been rated yet. After reading, feel free to leave comments and rate it.
Question: I need a code stub to connect from a C program to mysql. I have never used the mysql C API before.
Answer: The following should get you started. The source code is 'loader.c'.
Compile it with
gcc loader.c -o loader -I /usr/local/mysql/include -L /usr/local/mysql/lib -l mysqlclient
If you get error messages, check where your mysql is installed. Make sure that mysqlclient is on the lib search path.
 | |  | | #include <stdio.h>
#include <mysql.h>
int mysql_exec_sql(MYSQL *mysql,const char *create_definition) {
return mysql_real_query(mysql,create_definition,strlen(create_definition));
}
int main() {
MYSQL *mysql=NULL;
MYSQL_RES *result;
MYSQL_ROW row;
char sQuery[1000];
unsigned int num_fields;
int i;
if((mysql=mysql_init(mysql))==NULL) {
printf("\nFailed to initate MySQL connection");
exit(1);
}
if (!mysql_real_connect(mysql,"127.0.0.1","root","","qos",0,NULL,0)) {
printf( "Failed to connect to MySQL: Error: %s\n", mysql_error(mysql));
exit(1);
}
printf("Logged on to database sucessfully");
strcpy(sQuery, "select count(*) from traffic");
if(mysql_exec_sql(mysql,sQuery)==0) {
result = mysql_store_result(mysql);
if (result) {
num_fields = mysql_num_fields(result);
while ((row = mysql_fetch_row(result))) {
for(i = 0; i < num_fields; i++) {
printf("[%s] ", row[i]);
}
printf("\n");
}
mysql_free_result(result);
}
}
mysql_close(mysql);
printf("\nDone.\n");
}
| |  | |  |
Comments:
|