c++libpqxx

Extracting an username from the database


I'm relatively new to the pqxx library and so I can't seem to figure out how to get data out of the database.

I have my header file for the DBUser class

#pragma once
#include <string>
class DBUser
{
private:
    std::string m_user, m_password;
public:
    void CreateUser(std::string const& user, std::string const& pw);
    void LoginUser(std::string const& user, std::string const& pw);
};

and this is the cpp with the login implementation

#include "DBUser.h"
#include "DBLink.h"
#include <pqxx/pqxx>

void DBUser::CreateUser(std::string const& user, std::string const& pw)
{
    pqxx::work worker(*DBLink::GetInstance());
    try {
        worker.exec0("INSERT INTO users VALUES('" + user + "', " +
            "'" + worker.conn().encrypt_password(user, pw, "md5") + "')");
        worker.commit();
    }
    catch (const std::exception& e) {
        worker.abort();
        throw;
    }
}

void DBUser::LoginUser(std::string const& user, std::string const& pw)
{
    pqxx::work worker(*DBLink::GetInstance());
    try {
        pqxx::result username_result = worker.exec0("SELECT username FROM users WHERE username=" + 'user');
        worker.commit();
    }
    catch (const std::exception& e) {
        worker.abort();
        throw;
    }
}

Whenever I try to run the program I get an error in the xstring file from c++. I also tried getting the data necessary using the row class but to no success, the same error, so can somebody show me and explain how to output data from the database ?

Edit: Added the exact error im getting enter image description here


Solution

  • Okay, you're not going to want to do it that way. You should use positional arguments and prepared statements.

    Look at this page:

    https://libpqxx.readthedocs.io/en/6.4/a01480.html

    For instance, here's some code of mine:

    static constexpr char const * INSERT_LIST { "author_id, series_id" };
    
    void DB_AuthorSeries_Base::doInsert(pqxx::connection &conn, AuthorSeries &obj) {
        pqxx::work work {conn};
        string sql { string{"INSERT INTO author_series ("} + INSERT_LIST + ") VALUES (nullif($1, 0), nullif($2, 0)) RETURNING id" };
        pqxx::result results = work.exec_params(sql,
            obj.getAuthorId(),
            obj.getSeriesId());
        work.commit();
        obj.setId(results[0][0].as<int>());
    }
    

    Notice the $1, T2, etc.

    Now, I don't know if your insert statement is going to do what you want, as I always use createuser. BUT... It is a very very VERY bad habit to let your SQL calls have raw data in them. That's how SQL injection attacks where, where people write naughty data into your app in order to hack into your system.

    Never, never, never do that. Always have your data in prepared statements similar to what I'm showing here.