0

So I'm trying to build my sql statement in the for loop.
But on executing, it shows error at the very first point of the string.
Is the concatenation method wrong, cause I printed the sql statement and manually execute in postgresql and it works.

Also I had tried

char *sqlStatement = "INSERT INTO record()..VALUES();\
    INSERT INTO record()..VALUES();\
    INSERT INTO record()..VALUES();
"

That works.

Note that I have reduced the loop to only once and reduced the number of columns for brevity.

The code:

char sqlStatement[8000];
for(int i=0;i<1;i++) {
        sprintf(&sqlStatement[0] + strlen(sqlStatement), "INSERT INTO record (\"user_id\", \"filename\", \"ports\", \"timestamp\" ... )VALUES (1, 'example%d', 0, '123456789%d', ... );", i, i,);
}
pgResult = PQexec(pgConn, sqlStatement);
if (PQresultStatus(pgResult) != PGRES_COMMAND_OK) {
        printf("%s", PQresultErrorMessage(pgResult));
        PQclear(pgResult);
        closeSQL(pgConn);
        exit(-1);
}

Error message:

ERROR:  syntax error at or near ""
LINE 1: INSERT INTO captures ("user_id", "filename", "ports", "time...        
        ^

2 Answers 2

1

You're calling strlen(sqlStatement) but sqlStatement is uninitialized at that point. That's undefined behavior.

Put

sqlStatement[0] = '\0';

before the loop to start out with an empty string.

By the way, exit(-1) is wrong. The only standard C exit values are 0/EXIT_SUCCESS and EXIT_FAILURE. On Unix you can use any value between 0 and 255. I'm not sure about Windows but it's probably similar. I don't know any OS where -1 is valid.

Sign up to request clarification or add additional context in comments.

1 Comment

Ah...that solved my headache. Thanks! Will change the exit to the standard method too. :)
0
char sqlStatement[11111];
size_t_pos;

pos=0; 
pos += sprintf(sqlStatement+pos, "INSERT INTO record() VALUES(%s);\n" , "Argh!" );
pos += sprintf(sqlStatement+pos, "INSERT INTO record(...);\n" ... );
pos += sprintf(sqlStatement+pos, "INSERT INTO record(...);\n" ... );
...

A real program should of course first check the return value from sprintf, before using it to increment the pos position.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.