0

I'm new to C++ (limited SQL knowledge) and I'm having a difficult time inserting data into a postgresql.

char test1 = 'C'
w.exec("CREATE TABLE IF NOT EXISTS binary (id INT PRIMARY KEY, meta TEXT)");

w.exec("INSERT INTO binary (id,meta) VALUES (5, 'A')");
w.exec(std::string("INSERT INTO binary (id,meta) VALUES (6, ") + test1 + ")");
w.exec("INSERT INTO binary (id,meta) VALUES (7, "+readFile2("/home/test/cpp_db/rdb_test/test.txt")+")");

The first insert statement works fine. However the second statement results in the error:

ERROR:  column "c" does not exist

While the third insert statement results in the error:

ERROR:  column "thisisatest123" does not exist

I should mention that thisisatest123 is the content of the file. Why is it that the first insert statement saves the character A fine but the other two sql statements fail? I've looked into INSERT COMMAND :: ERROR: column "value" does not exist hence I made sure test1 is enclosed by single quotes but it doesn't seem to make a difference.

What do I need to do such that I can insert the content of a file into the database? Ie, the third insert statement.

Mark
  • 113
  • 7
  • The second insertion fails because you forgot to escape `'C'`: try `w.exec(std::string("INSERT INTO binary (id,meta) VALUES (6, '") + test1 + "')");` instead. – heap underrun Mar 21 '21 at 22:55
  • The same problem is with the third insertion statement: you didn't escape the string you read from file. Try `w.exec("INSERT INTO binary (id,meta) VALUES (7, '"+readFile2("/home/test/cpp_db/rdb_test/test.txt")+"')");` – heap underrun Mar 21 '21 at 22:58
  • Thanks, that fixed the second insertion. – Mark Mar 21 '21 at 23:00
  • Thank you. I obviously have a long way to go to being competent with C++. – Mark Mar 21 '21 at 23:03
  • Also note that `char test1 = 'C';` means that `test1` is a **single** character `C`. If you want `test1` to be the string `'C'` then use either `char test1[] = "'C'";` or `std::string test1 = "'C'";` instead. – heap underrun Mar 21 '21 at 23:03
  • You need single quotes around a string literal, but what you are trying to do is prone to SQL injection attacks. What API are you using? Use a prepared statement. – Laurenz Albe Mar 22 '21 at 05:01

0 Answers0