34 std::cout <<
"=== basic_connection example ===" << std::endl;
39 auto context = std::make_shared<database_context>();
42 auto db_manager = std::make_shared<database_manager>(context);
46 if (!db_manager->set_mode(database_types::postgres))
48 std::cerr <<
"Failed to set database mode to PostgreSQL" << std::endl;
51 std::cout <<
"Database mode set to PostgreSQL" << std::endl;
55 std::string connection_string
56 =
"host=localhost port=5432 dbname=example_db user=user password=password";
58 std::cout <<
"Connecting to database..." << std::endl;
59 auto connect_result = db_manager->connect_result(connection_string);
61 if (!connect_result.is_ok())
63 std::cerr <<
"Connection failed. Make sure PostgreSQL is running and\n"
64 <<
"the connection string is correct.\n"
65 <<
"Connection string format:\n"
66 <<
" host=<host> port=<port> dbname=<db> user=<user> password=<pass>"
70 std::cout <<
"Connected successfully" << std::endl;
73 std::string create_sql = R
"(
74 CREATE TABLE IF NOT EXISTS greetings (
75 id SERIAL PRIMARY KEY,
76 message VARCHAR(200) NOT NULL
80 auto create_result = db_manager->create_query_result(create_sql);
81 if (create_result.is_ok())
83 std::cout <<
"Table 'greetings' is ready" << std::endl;
87 std::cerr <<
"Failed to create table" << std::endl;
91 auto insert_result = db_manager->execute_query_result(
92 "INSERT INTO greetings (message) VALUES ('Hello from database_system!')");
94 if (insert_result.is_ok())
96 std::cout <<
"Row inserted" << std::endl;
101 = db_manager->select_query_result(
"SELECT id, message FROM greetings ORDER BY id");
103 if (select_result.is_ok())
105 const auto& rows = select_result.value();
106 std::cout <<
"Query returned " << rows.size() <<
" row(s):" << std::endl;
108 for (
const auto& row : rows)
110 for (
const auto& [column, value] : row)
112 std::cout <<
" " << column <<
" = ";
113 std::visit([](
const auto& v) { std::cout << v; }, value);
114 std::cout << std::endl;
120 std::cerr <<
"Select query failed: " << select_result.error().message << std::endl;
124 db_manager->disconnect_result();
125 std::cout <<
"Disconnected" << std::endl;
127 std::cout <<
"=== basic_connection example completed ===" << std::endl;
Dependency injection container for database system components.