Re: Insert and Retrieve unsigned char sequences using C

From: Merlin Moncure <mmoncure(at)gmail(dot)com>
To: Vinícius Soares <viniciusams(at)yahoo(dot)com(dot)br>
Cc: PostgreSQL General <pgsql-general(at)postgresql(dot)org>
Subject: Re: Insert and Retrieve unsigned char sequences using C
Date: 2010-07-22 19:20:07
Message-ID: AANLkTinJ1tlqtsmKo7rFaEGDFtwqRbSA81wgHHrACN_l@mail.gmail.com
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-general

2010/7/22 Vinícius Soares <viniciusams(at)yahoo(dot)com(dot)br>:
> Hey,
>
> thanks for your response.
> I did it:
>
>         S8 sql[1500] = "insert into t values ( E'";
>         U8 *msg;
>         msg = PQescapeByteaConn(conn, pending_cmd->cmd.value,
> sizeof(msg_cmd_t), &to_length);
>         for (i=0; i < sizeof(msg_cmd_t); i++){
>             S8 str[20] = "";
>             sprintf(str, "%c", *(msg+i) );
>             strcat(sql, str);
>         }
>         strcat(sql, "' );");
>         PQexec(conn, sql);
>
> But it is very strange because sometimes it works but others times it does
> not work.
> is it right?

That code doesn't look right: you need to make sure your 'to' is big
enough: at has to be at least (2*N)+1 where N is the input size. it
returns a size_t, not a char*, and you should be able to just sprintf
the 'to' into your query, not copy the chars in a loop. see the
following fragment:

#define ARGSZ 64
char my_bytea[ARGSZ];
char escaped_bytea[(2*ARGSZ)+1];
int error;
size_t nbytes;

nbytes = PQescapeStringConn (conn, escaped_bytea, my_bytea,
sizeof(my_bytea), &error);

if(error != 0)
// handle error

sprintf(querybuf, "insert into foo(bytea_col) values (E'%s')", escaped_bytea);

like I said earlier, this is just about the absolute worst way to
transfer a bytea to the server. I had to look up the docs for
PQescapeStringConn -- I've never once used it my entire life (or it's
even more evil cousin, PQescapeString).

merlin

In response to

Browse pgsql-general by date

  From Date Subject
Next Message Tim Landscheidt 2010-07-22 19:21:41 Re: How to distribute quantity if same product is in multiple rows
Previous Message Alvaro Herrera 2010-07-22 18:39:02 Re: Are identical subqueries in unioned statements nonrepeatable?