How to interact with 2 databases in C using MySQL? - mysql

I am currently working on a project where I have to count runners. At some point, I have to transfer the data from my local Database (mysqlLocal) to the one of the High School I'm working in (mysqlLycee).
I think doing this was a good idea, but for some reason I have a segfault when executing the program.
#include <stdio.h>
#include <stdlib.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netdb.h>
#include <netinet/in.h>
#include <unistd.h>
#include <string.h>
#include <mysql.h>
int main(int argc, char *argv[]){
MYSQL mysqlLocal;
MYSQL_RES *result = NULL;
MYSQL_ROW row;
char requete[150];
int num_champs;
char noParticipant[5];
char kmParcourus[3];
mysql_init(&mysqlLocal);
if(!mysql_real_connect(&mysqlLocal,"127.0.0.1","root","debianCCF","localCCF",0,NULL,0))printf("Error on first connect");
sprintf(requete,"SELECT NO_PARTICIPANT, KMPARCOURUS FROM PARTICIPANTS WHERE NO_COURSE = %s",argv[5]);
if(!mysql_query(&mysqlLocal,requete))printf("Error on first query");
result = mysql_use_result(&mysqlLocal);
num_champs=mysql_num_fields(result);
mysql_close(&mysqlLocal);
MYSQL mysqlLycee;
mysql_init(&mysqlLycee);
if(!mysql_real_connect(&mysqlLycee,argv[1],argv[2],argv[3],argv[4],0,NULL,0))printf("Error on second connect");
int i;
while ((row = mysql_fetch_row(result))){
unsigned long *lengths;
lengths = mysql_fetch_lengths(result);
for(i=0;i<num_champs;i++){
if(i==0)sprintf(noParticipant,"%.*s", (int) lengths[i], row[i] ? row[i] : "NULL");
if(i==1)sprintf(kmParcourus,"%.*s", (int) lengths[i], row[i] ? row[i] : "NULL");
}
sprintf(requete,"UPDATE PARTICIPANTS SET KMPARCOURUS=%s WHERE NO_PARTICIPANT=%s",kmParcourus,noParticipant);
if(!mysql_query(&mysqlLycee,requete))printf("Error on second query");
}
mysql_free_result(result);
mysql_close(&mysqlLycee);
return 0;
}
I'm working on Debian 8, and compiling with the following command :
gcc updateLycee.c -o updateLycee -lmysqlclient -L/usr/lib64/mysql -I/usr/include/mysql;
EDIT: added mysql checks, but still segfault when starting the program.

You close your connection to the local database, and then later try to fetch rows from a result set associated with that connection. That will not work.
If you want to transfer data from one DB to the other then you must either
first slurp all the wanted data from one DB into memory (fetch all the rows and store the contents you need in ordinary arrays, for instance), OR
hold connections to both databases open at the same time.

Related

How to connect and code a C Program with a MySQL database in Windows?

I have recently learned MySQL and I want to implement the knowledge on how to build a C Program using MySQL database on windows. Can anyone provide me with a detailed description on which files to download and whether I need XAMPP running or not?
I have tried to read the documentation here : https://dev.mysql.com/doc/refman/8.0/en/c-api-implementations.html . However , I couldn't figure out for my life how to do it on Windows.(Seems pretty easy for Linux, unfortunately I do not have a Linux machine)
It would be great if someone would provide me with a detailed and step by step explanation. Thanks in advance.
I know how the code would look like.
#include <stdio.h>
#include <stdlib.h>
#include <my_global.h>
#include <mysql.h>
typedef struct
{
char host[20];
char user[25];
char pass[50];
}DB_CONN_PARAMS;
MYSQL * connect_db(DB_CONN_PARAMS *params)
{
MYSQL *connection = mysql_init(NULL);//init connection
if (connection == NULL)
{//check init worked
fprintf(stderr, "%s\n", mysql_error(connection));
exit(EXIT_FAILURE):
}
//connect:
if (mysql_real_connect(
connection,
params->host,
params->user,
params->pass,
NULL,0,NULL,0)
==NULL)
{//connection failed?
fprintf(stderr, "%s\n", mysql_error(connection));
mysql_close(connection);
exit(EXIT_FAILURE):
}
return connection;
}
int main()
{
MYSQL *db;
DB_CONN_PARAMS *params = calloc(1,sizeof(DB_CONN_PARAMS));
//just an alternative way of passing connection params, find a struct easier
params->host = "127.0.0.1";
params->user = "root";
params->pass = "mySuperSecretPass";
MYSQL * connect_db(DB_CONN_PARAMS *params);
db = connect_db(params);
//we don't need the struct anymore
free(params);
params = NULL;
//do stuff
mysql_close(db);//close connection, of course!
return EXIT_SUCCESS;
}
I just need help with the setup.

Memory mapping in Octave with mex-functions

I have a plain C code (running on Linux) and I would like to implement it in Octave, so I thought I could use a mex-file for handling the memory mapping and send the information I received (or send) back and forth to my script in Octave and my sensors. The C code looks like this:
#include <stdio.h>
#include <stdint.h>
#include <stdlib.h>
#include <poll.h>
#include <fcntl.h>
#include <errno.h>
#include <unistd.h>
#include <sys/mman.h>
#define CUSTOM_IP_MAP_SIZE 0x10000
#define CUSTOM_IP_BASEADDR 0x43C00000
#define CUSTOM_IP_S00_AXI_SLV_REG0_OFFSET 0
#define CUSTOM_IP_S00_AXI_SLV_REG1_OFFSET 4
int main(void)
{
uint32_t leds=0x0;
int fd = open("/dev/uio0", O_RDWR);
void *ptr;
if (fd < 0) {
perror("open");
exit(EXIT_FAILURE);
}
ptr = mmap(NULL, CUSTOM_IP_MAP_SIZE, PROT_READ|PROT_WRITE, MAP_SHARED, fd, 0);
while (1) {
leds = *((unsigned *)(ptr + CUSTOM_IP_S00_AXI_SLV_REG1_OFFSET)); //Read from the IP (slv_reg1).
*((unsigned *)(ptr + CUSTOM_IP_S00_AXI_SLV_REG0_OFFSET)) = leds; //Write to the IP (slv_reg0).
}
close(fd);
exit(EXIT_SUCCESS);
}
I compiled the code with no errors and the following command:
mkoctfile --mex mmap.c
I get the following error when I run it in Octave:
error: failed to install .mex file function 'mmap'
Should I keep trying to do this with a mex-function or there is other option better for this?
Thank you for any help.

Using c to insert variables in mysql database

I am trying to insert variable calculated in my C program using mysql API . Despite trying all types of tricks( single quote , double quotes , query placeholder) I am not able to enter the data. The libraries used are:
#include <stdio.h>
#include <stdlib.h>
#include <netdb.h>
#include <netinet/in.h>
#include <math.h>
#include <my_global.h>
#include <mysql.h>
The relevant bits of code are
MYSQL *con = mysql_init(NULL);
if (mysql_real_connect(con, "localhost", "test", "test123",
"transport", 0, NULL, 0) == NULL)
{
finish_with_error(con);
}
if (mysql_query(con, "INSERT INTO gps_points(vehicle_id,lat,lon,speed) VALUES(unit_id_dec,lat,lon,speed_float)"))
{
finish_with_error(con);
}
mysql_close(con);
I am getting the following error:
Unknown column 'unit_id_dec' in 'field list'
The compile options used are:
sudo gcc socketListen.c -o listenSock -lm `mysql_config --cflags --libs`
Any solutions?
To solve this error you will need either rewrite trigger and remove 'unit_id_dec' variable or alter table and add variable 'unit_id_dec'.
Here's link how to rewrite trigger.
I have researched and found that following solution is working :
char buf[1024] = {};
char query_string[] = {
"INSERT INTO gps_points(vehicle_id,lat,lon,speed) VALUES(%u,%.4f,%.4f,%.2f)"
};
sprintf(buf, query_string,unit_id_dec,lat,lon,speed_float);
if (mysql_query(con,buf))
{
finish_with_error(con);
}

"unable to include mysql.h" in C program [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
How to make #include <mysql.h> work?
I need to connect C and mysql
This is my program
#include <stdio.h>
#include <mysql.h>
#define host "localhost"
#define username "root"
#define password "viswa"
#define database "dbase"
MYSQL *conn;
int main()
{
MYSQL_RES *res_set;
MYSQL_ROW row;
conn = mysql_init(NULL);
if( conn == NULL )
{ `
printf("Failed to initate MySQL\n");
return 1;
}
if( ! mysql_real_connect(conn,host,username,password,database,0,NULL,0) )
{
printf( "Error connecting to database: %s\n", mysql_error(conn));
return 1;
}
unsigned int i;
mysql_query(conn,"SELECT name, email, password FROM users");
res_set = mysql_store_result(conn);
unsigned int numrows = mysql_num_rows(res_set);
unsigned int num_fields = mysql_num_fields(res_set);
while ((row = mysql_fetch_row(res_set)) != NULL)
{
for(i = 0; i < num_fields; i++)
{
printf("%s\t", row[i] ? row[i] : "NULL");
}
printf("\n");
}
mysql_close(conn);
return 0;
}
I got the error "unable to include mysql.h".
I am using windows 7, Turbo C, mysql and I downloaded mysql-connector-c-noinstall-6.0.2-win32-vs2005, but I don't know how to include it.
Wrong syntax. The #include is a C preprocessor directive, not a statement (so should not end with a semi-colon). You should use
#include <mysql.h>
and you may need instead to have
#include <mysql/mysql.h>
or to pass -I /some/dir options to your compiler (with /some/dir replaced by the directory containing the mysql.h header).
Likewise, your #define should very probably not be ended with a semi-colon, you may need
#define username "root"
#define password "viswa"
#define database "dbase"
I strongly suggest reading a good book on C programming. You may want to examine the preprocessed form of your source code; when using gcc you could invoke it as gcc -C -E
yoursource.c to get the preprocessed form.
I also strongly recommend enabling warnings and debugging info (e.g. gcc -Wall -g for GCC). Find out how your specific compiler should be used. Learn also how to use your debugger (e.g. gdb). Study also existing C programs (notably free software).
You should learn how to configure your compiler to use extra include directories, and to link extra libraries.
N.B. With a linux distribution, you'll just have to install the appropriate packages and perhaps use mysql_config inside our Makefile (of course you'll need appropriate compiler and linker flags), perhaps with lines like
CFLAGS += -g -Wall $(shell mysql_config --cflags)
LIBES += $(shell mysql_config --libs)
added to your Makefile.

Libmysqld Crashes On Start

I tried to create a very simple application using the MySQL embedded server.
I basically took the simple example from the MySQL documentation and modified it a bit.
#include <stdio.h>
#include <stdlib.h>
#include <stdarg.h>
#include "mysql.h"
MYSQL *mysql;
static char *server_options[] = { "mysql_test", "--datadir=/Users/admin/libmysqldtest", "--language=/Users/admin/libmysqldtest/german", NULL };
int num_elements = (sizeof(server_options) / sizeof(char *)) - 1;
static char *server_groups[] = { "libmysqld_server", "libmysqld_client", NULL };
int main(void)
{
mysql_library_init(num_elements, server_options, server_groups);
mysql = mysql_init(NULL);
mysql_options(mysql, MYSQL_READ_DEFAULT_GROUP, "libmysqld_client");
mysql_options(mysql, MYSQL_OPT_USE_EMBEDDED_CONNECTION, NULL);
//Do some queries here...
mysql_close(mysql);
mysql_library_end();
return 0;
}
On start-up
mysql_embedded: Unknown error 1146
is logged and InnoDB initializes.
Afterwards the app crashes at mysql_init.
Linking against libmysqld-debug I get the following error message:
Assertion failed: (argc && *argc >= 1), function handle_options, file
/Volumes/hd2/pb2/build/sb_0-3198286-1302522144.5/mysql-5.5.12/mysys/my_getopt.c, line 167
I use the static libmysqld(-debug) library distributed with the community server TAR-Archive for Mac OS X from the MySQL website (64 bit).