Anže Lukežič Anže Lukežič - 1 year ago 78
MySQL Question

C language variable type float and integer pass in mysql

I'm a beginner in C and mysql programing.For some days now I am trying to write float and integer values that i get from sensors to a database in mySQL.So far i'm just getting an error "too many arguments to function ‘mysql_query’" and " expected ‘const char *’".Below is my simple code.

int main()
int var1 = 1;
float var2 = 5.1;
MYSQL *conn;

conn = mysql_init(NULL);
if (!mysql_real_connect(conn, host, user, pass, dbname,port, unix_socket, flag))
fprintf(stderr, "\nError: %s [%d]\n",mysql_error(conn),mysql_errno(conn));
printf("Connection successful!\n");
mysql_query(conn,"INSERT INTO variables (var1) VALUE ('%d');",var1);
mysql_query(conn, mysql_query );

Answer Source

It's a nice idea, but mysql_query doesn't work with variable arguments.

You need to store the query in a buffer:

char buff[1024];

snprintf(buff, sizeof buff, "INSERT INTO variables (var1) VALUES  ('%d');",var1);

and then you can call mysql_query with this buffer:

mysql_query(conn, buff);

EDIT: As pointed out by @PaulOgilvie: Notice VALUES instead of VALUE in the query.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download