如何通过C++使用PostgreSQL将变量插入到数据库表中?

问题描述:

我有一个将数值插入数据库表的C++程序。我不能直接对数据进行硬编码,因为数据不断更新,但我对语法非常困惑。 当我尝试这样做:如何通过C++使用PostgreSQL将变量插入到数据库表中?

l.exec("INSERT INTO course VALUES(cid, term, 'subj',crse, sec, 'units', 'instructors');"); 
      l.exec("INSERT INTO meeting VALUES(cid, term, 'type', 'days', 'time', 'build', room);"); 
      l.exec("INSERT INTO enrolledin VALUES(cid, term, sid, 'major', 'classlevel', 'level', 'status', seat, numunits, 'grade');"); 
      l.exec("INSERT INTO student VALUES(sid, 'surname', 'prefname', 'email');"); 

I get this error: 
terminate called after throwing an instance of 'pqxx::undefined_column' 
    what(): ERROR: column "cid" does not exist 
LINE 1: INSERT INTO course VALUES(cid, term, 'subj',crse, se... 

          ^
HINT: There is a column named "cid" in table "course", but it cannot be referenced from this part of the query. 

- 有人告诉我,那是因为我将代替字符串中的数值文字串名字,我很困惑,如何插入通过C++字符串中的值仍然使用变量名称。

+0

对不起,去掉了MySQL的标签 – user5943954

使用的SQL查询INSERT的语法不正确。它应该是:

INSERT INTO course (cid, subj) VALUES(1, 'subj'); 

您应该指定表名以及要插入的列以及之后的值。为了简单起见,我减少了列数。有关INSERT查询的完整语法,请检查PostgreSQL documentation

要从变量插入值,你可以做到以下几点:

int cidValue = 1; 
std::string subjValue = "subj"; 

l.exec("INSERT INTO course (cid, subj) VALUES(" + std::to_string(cidValue) + ", '" + l.esc(subjValue) + "')"); 

esc()功能有助于防止SQL注入攻击。

+0

当你在插入VS双引号做单引号? cid是一个整数,subj是一个字符串?我们将哪种类型的单引号括起来? – user5943954

+0

@ user5943954双引号用于指定[C++字符串文字](http://en.cppreference.com/w/cpp/language/string_literal)。 SQL查询中字符串值所需的单引号。 – Nikita

+1

你已经非常帮助了,非常感谢你! – user5943954