lonesome
lonesome

Reputation: 19

MySQL: Insert values to column using C

I have put the value coming out of the the packet[i] from the for loops in variables d,e f,j. but when I am trying to put the values of these variables in a column of mysql I get an error

Unknown column 'd' in 'field list'

My code:

printf("\nResponse Code: ");

for(i = 54; i<=56; i++)
{       
    d = packet[i];
    printf("%c", packet[i]);
 }
printf("\nCommand: ");
for(i = 54; i<=57; i++)
    {       
    e = packet[i];
    printf("%c", packet[i]);
}

printf("\nResponse Parameter: ");

for(i = 58; i<=104; i++)
{       
    f = packet[i];
    printf("%c", packet[i]);
}

printf("\nTime to live:");
j = packet[22];
printf("%c", packet[i]); 

if (mysql_query(con, "CREATE TABLE SMTP(Response_Code CHAR(250) , Command CHAR(250), Response_Parameter CHAR(250), Time_to_live CHAR(250))"))         {      
     finish_with_error(con);
  }
  printf("here");
  if (mysql_query(con, "INSERT INTO SMTP VALUES(d,e,f,j)")) {
  finish_with_error(con);
  }

I want the values of d e f and j to be printed in these columns but I am getting error Unknown column 'd' in 'field list'

Upvotes: 1

Views: 95

Answers (1)

kiran Biradar
kiran Biradar

Reputation: 12732

You can use snprintf or sprintf to form the query, before to that extract the complete data instead of single char from the packet.

char d[100], e[100], f[100];


printf("\nResponse Code: ");
 for(i = 54; i<=56; i++)
 {       
    d[i-54] = packet[i];  //Copy the individual char
    printf("%c", packet[i]);
 }
 d[i-54] = '\0';  //null terminate the array



printf("\nCommand: ");
for(i = 54; i<=57; i++)
{       
    e[i-54] = packet[i];
    printf("%c", packet[i]);
}
e[i-54] = '\0';


printf("\nResponse Parameter: ");
for(i = 58; i<=104; i++)
{       
    f[i-58] = packet[i];
    printf("%c", packet[i]);
 }
 f[i-58] = '\0';

//do the same for even "Time to live"

Then form the prepared statement and execute it,

char query[300];
sprintf(query, "INSERT INTO SMTP VALUES (?,?,?)");

MYSQL_STMT    *stmt;
MYSQL_BIND    bind[3];

stmt = mysql_stmt_init(con);
if (!stmt)
{
    return;//error
}
if (mysql_stmt_prepare(con, query, strlen(query)))
{
    return;//error
}

int dLen = strlen(d);
bind[0].buffer_type= MYSQL_TYPE_STRING;
bind[0].buffer= (char *)d;
bind[0].buffer_length= STRING_SIZE;
bind[0].is_null= 0;
bind[0].length= &dLen;

 int eLen = strlen(e);
bind[1].buffer_type= MYSQL_TYPE_STRING;
bind[1].buffer= (char *)e;
bind[1].buffer_length= STRING_SIZE;
bind[1].is_null= 0;
bind[1].length= &eLen ;

 int fLen = strlen(f);
bind[2].buffer_type= MYSQL_TYPE_STRING;
bind[2].buffer= (char *)f;
bind[2].buffer_length= STRING_SIZE;
bind[2].is_null= 0;
bind[2].length= &fLen;

/* Execute the INSERT statement - 1*/
if (mysql_stmt_execute(stmt))
{
  return; //error
}

 mysql_stmt_close(stmt

Upvotes: 1

Related Questions