#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
class DBConn {
private:
int id;
DBConn(int conn_id) : id(conn_id) {
cout << "Connection " << id << " established.\n";
}
~DBConn() {
cout << "Connection " << id << " closed.\n";
}
public:
void query(const string& sql) {
cout << "Executing on Connection " << id << ": " << sql << endl;
}
friend class ConnManager; // Only ConnManager can create/destroy
};
class ConnManager {
private:
static vector<DBConn*> connections;
static int connCounter;
public:
// Get a new database connection
static DBConn* getConn() {
DBConn* conn = new DBConn(++connCounter);
connections.push_back(conn);
return conn;
}
// Release a specific connection
static void releaseConn(DBConn* conn) {
auto it = find(connections.begin(), connections.end(), conn);
if (it != connections.end()) {
delete *it;
connections.erase(it);
cout << "Connection released.\n";
}
else
cout << "Invalid connection!\n";
}
// Close all connections
static void shutdownAll() {
cout << "Shutting down all connections\n";
for (DBConn* conn : connections) {
delete conn;
}
connections.clear();
cout << "All connections closed.\n";
}
};
// Static variable initialization
vector<DBConn*> ConnManager::connections;
int ConnManager::connCounter = 0;
// Driver Code
int main() {
cout << "\n--- Creating Database Connections ---" << endl;
DBConn* db1 = ConnManager::getConn();
DBConn* db2 = ConnManager::getConn();
db1->query("SELECT * FROM users");
db2->query("UPDATE users SET active = 1");
cout << "\n--- Releasing One Connection ---" << endl;
ConnManager::releaseConn(db1);
cout << "\n--- Shutting Down All Connections ---" << endl;
ConnManager::shutdownAll();
return 0;
}