如何使用C ++和libpqxx确定postgres中表的主键?

时间:2019-05-16 14:10:13

标签: c++ postgresql libpqxx

我的任务是使用libpqxx(动态地)确定postgres表的主键,但是我不知道如何正确绑定该值。我收到语法错误。

std::string sql =
           "SELECT c.column_name, c.data_type "\
            "FROM information_schema.table_constraints tc" 
            "JOIN information_schema.constraint_column_usage AS ccu USING (constraint_schema, constraint_name)" 
            "JOIN information_schema.columns AS c ON c.table_schema = tc.constraint_schema "
            "AND tc.table_name = c.table_name AND ccu.column_name = c.column_name "
            "WHERE constraint_type = 'PRIMARY KEY' and tc.table_name = '$1';";


     C->prepare("determine_primary_key", sql.c_str()); 

     pqxx::prepare::invocation  w_invocation = W->prepared("determine_primary_key");


    std::vector<std::string > vect;

    vect.push_back("postgres_table_name");

    prep_dynamic(vect, w_invocation);

    pqxx::result r = w_invocation.exec();

1 个答案:

答案 0 :(得分:0)

从pqxx的文档中,弃用了prepared()方法。因此,使用您的代码段,我将进行以下更改以使用新的exec_prepared()语句并输入您的参数:

std::string sql =
       "SELECT c.column_name, c.data_type "\
        "FROM information_schema.table_constraints tc" 
        "JOIN information_schema.constraint_column_usage AS ccu USING (constraint_schema, constraint_name)" 
        "JOIN information_schema.columns AS c ON c.table_schema = tc.constraint_schema "
        "AND tc.table_name = c.table_name AND ccu.column_name = c.column_name "
        "WHERE constraint_type = 'PRIMARY KEY' and tc.table_name = '$1';";


 C->prepare("determine_primary_key", sql.c_str()); 

 pqxx::result r = W->exec_prepared("determine_primary_key", "<your_table_name_here>");

但是,如果您仍在使用旧版本的pqxx,并且需要继续使用prepared(),则可以执行以下操作:

std::string sql =
       "SELECT c.column_name, c.data_type "\
        "FROM information_schema.table_constraints tc" 
        "JOIN information_schema.constraint_column_usage AS ccu USING (constraint_schema, constraint_name)" 
        "JOIN information_schema.columns AS c ON c.table_schema = tc.constraint_schema "
        "AND tc.table_name = c.table_name AND ccu.column_name = c.column_name "
        "WHERE constraint_type = 'PRIMARY KEY' and tc.table_name = '$1';";

 C->prepare("determine_primary_key", sql.c_str()); 

 pqxx::result r = W->prepared("determine_primary_key")("<your_table_name_here>").exec();

您可以查看libpqxx文档以获取有关prepared()exec_prepared()的更多信息。