Question

ERROR:  syntax error at or near "\"
LINE 1: \copy mytable FROM urishFile WITH (FORMAT csv, DELIMITER ','...
        ^

I am getting this error when running command from c++ program.

command = "\\copy mytable FROM urishFile WITH (FORMAT csv, DELIMITER ',',  NULL 'NULL');";
executCommand(conn, command);

void executCommand(PGconn *conn, std::string command) {
    PGresult   *res;                                    // holds query result 
    res = PQexec(conn, command.c_str());
    if (PQresultStatus(res) != PGRES_COMMAND_OK) {
        fprintf(stderr, "%s", PQerrorMessage(conn));
        PQclear(res);
        exit_nicely(conn);
    }
    PQclear(res);       
}

When running the same command from psql prompt, it works without errors.

mydatabase=> \copy mytable FROM urishFile WITH (FORMAT csv, DELIMITER ',',  NULL 'NULL');

What I have done wrong?

Was it helpful?

Solution

\copy is a psql command, not an SQL command. psql commands only work inside the psql shell. Since you're talking directly to the database, you'd need to use the COPY SQL command. However, COPY usually works with the server's file system rather than the client's:

COPY with a file name instructs the PostgreSQL server to directly read from or write to a file. The file must be accessible to the server and the name must be specified from the viewpoint of the server. When STDIN or STDOUT is specified, data is transmitted via the connection between the client and the server.

You'll probably need to use the STDIN option and PQputCopyData to send the data over to the PostgreSQL server.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top