抽象数据库的c++实现

Abstract database implementation in C++

本文关键字:实现 c++ 数据库 抽象      更新时间:2023-10-16

我想创建抽象的Db类,并通过继承Db实现Pg (postgresql):

Db.h :

template <class T>
class Db 
{
public:
    Db(std::string, std::string, std::string, std::string);
    virtual ~Db();
protected:
    T* getConnection();
    std::string getHost();
    std::string getUsername();
    std::string getDatabase();
    std::string getPassword();
    virtual std::string getConnectionString()=0;
private: 
    T* connection;
    std::string host;
    std::string username;
    std::string database;
    std::string password;
};

Db.cpp :

#include "Db.h"
using namespace std;
template <class T>
Db<T>::Db(string iHost, string iUsername, string iDatabase, string iPassword) 
    : host(iHost), username(iUsername), database(iDatabase), password(iPassword) {
    T* conn(getConnectionString());
    connection = conn;
}
template <class T>
T* Db<T>::getConnection() {
    return connection;
}
... getters

Pg.h :

#include "../Db.h"
template <class T>
class Pg : public Db<T> {
public:
    virtual std::string getConnectionString();
};

Pg.cpp :

#include "Pg.h"
template <class T>
std::string Pg<T>::getConnectionString() {
    return "host=" + this->getHost() + " user=" + this->getUsername() 
        + " password=" + this->getPassword() + " dbname=" + this->getDatabase();
}

main.cpp :

#include <iostream>
#include <pqxx/connection>
#include <pqxx/transaction>
#include "lib/db/pg/Pg.h"
using namespace std;
int main () {
    string host     = "localhost";
    string username = "username";
    string database = "db";
    string password = "root";
    try {
        Pg<pqxx::connection> *db(host, username, database, password);
    } catch (pqxx::broken_connection) {
        cout << "Failed to establish connection." << endl;
    }
    return 0;
}

很抱歉长时间的实现。在用g++编译之后,我得到了一个错误:

main.cpp: In function ‘int main()’:
main.cpp:15:62: error: expression list treated as compound expression in initializer [-fpermissive]
   Pg<pqxx::connection> *db(host, username, database, password);
                                                              ^
main.cpp:15:62: error: cannot convert ‘std::string {aka std::basic_string<char>}’ to ‘Pg<pqxx::basic_connection<pqxx::connect_direct> >*’ in initialization

我不知道这是不是一个好主意,因为我的第一个版本只有main()函数看起来更紧凑。我只是试图隐藏连接细节的地方,如连接字符串。

main()中,您的db变量被声明为指针。你不能像现在这样把构造函数参数传递给指针。

你需要:

  1. 从声明中删除*:

    Pg<pqxx::connection> db(host, username, database, password);
    
  2. 保留*,使用new来构造对象:

    Pg<pqxx::connection> *db = new Pg<pqxx::connection>(host, username, database, password);
    ...
    delete db;