C program to add data to MYSQL database - No results added

I am trying to create a C program to add data to my MYSQL database, and I would like to use the variables in the SQL string. I want to insert UNIX time (era) in one column, and the result from the energy meter in another (double)

Despite the fact that it builds without errors or warnings, I can not get it to insert data into the table. Can someone give me a hint where to look?

Thank you for all the help I can get, as I have been pretty busy in the dark.

Regards, Michael

#include <stdio.h>
#include <stdint.h>
#include <string.h>
#include <time.h>
#include <math.h>
#include <mysql.h>
#include <my_global.h>
#include <stdlib.h> // For exit function

int loggingok;   // Global var indicating logging on or off
double result = 323.234567; //Debug
double actual_time_sec;

void calculate_watts(void)
{
MYSQL *conn  = mysql_init(NULL);
char *server = "localhost";
char *user = "root";
char *password = "password"; /* set me first */
char *database = "power";
char SQL_String[100];
char time_char[11];
char result_char[11];

time_t actual_time;

actual_time = time(0);
actual_time_sec = difftime(actual_time,0);

sprintf(time_char,"%g",actual_time_sec);
sprintf(result_char,"%g",result);

printf("Tid: %g\n",actual_time_sec); //Debug
printf("Resultat: %g\n", result); //Debug

strcpy(SQL_String, "INSERT INTO consumption(time,consumption) VALUES(");
strcat(SQL_String, time_char);
strcat(SQL_String, ",");
strcat(SQL_String, result_char);
strcat(SQL_String, ")");

printf("SQL: %s", SQL_String); //Debug

// SQL_String = "INSERT INTO consumption(time,consumption) VALUES('"+ actual_time_sec +"',"+ result +")";

            if (!mysql_real_connect(conn, server, user, password, database, 0, NULL, 0)) {
                        fprintf(stderr, "%s\n", mysql_error(conn));
                        exit(1);  }
                if (mysql_query(conn, SQL_String)) {
                            fprintf(stderr, "%s\n", mysql_error(conn));
                            exit(1);  }
 }

int  main (int argc, char *argv[])
{
    printf(argv[1]); //Debug

    if(strcmp(argv[1], "db")) {
        loggingok=1;
        printf("Efergy E2 Classic decode \n\n");
        calculate_watts(); }

    else {
        loggingok=0; }

    return 0;
}
+4
source share
2 answers

Thanks, I will try as soon as I can

Regards, Michael

0
source

...

http://php.net/mysql_query. sprintf . sprintf, 2 , SQL.

$query = sprintf("SELECT firstname, lastname, address, age FROM friends 
    WHERE firstname='%s' AND lastname='%s'",
    mysql_real_escape_string($firstname),
    mysql_real_escape_string($lastname));

// Perform Query
$result = mysql_query($query);

// Check result
// This shows the actual query sent to MySQL, and the error. Useful for debugging.
if (!$result) {
    $message  = 'Invalid query: ' . mysql_error() . "\n";
    $message .= 'Whole query: ' . $query;
    die($message);
}

, if (! $result) , . , , mysql_error, , , .

-1

All Articles