2014-09-30 89 views
4

我想構建一個C程序來添加數據到我的MYSQL數據庫,我想使用SQL字符串中的變量。我想在一列中插入UNIX時間(epoch),並將能量表的結果插入另一列(雙精度)C程序添加數據到MYSQL數據庫 - 沒有添加結果

即使它的構建沒有錯誤或警告,我也無法將它插入到表中。有人能給我一個暗示的地方嗎?

感謝所有幫助我能爲我幾乎在黑暗

問候摸索, 的Mikael

#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; 
} 
+0

用你的邏輯,應該不會是'如果(!的mysql_query(康涅狄格州,SQL_String)){'呢? – VMai 2014-09-30 20:10:19

回答

-1

這裏是一個很好的例子......

http://php.net/mysql_query。請注意這裏使用sprintf。第二個和第三個參數與sprintf一起使用,將這兩個參數中的數據精確放置在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重新設置的文本將放置在消息變量中,然後在應用程序死亡時顯示。

0

謝謝,我會嘗試,只要我能

問候, 的Mikael