C++ table与数据库的交互方式

   2024-09-30 4830
核心提示:在C++中,与数据库进行交互通常需要使用数据库连接库。这些库允许你在C++程序中执行SQL查询并处理结果。以下是一些常见的数据库

在C++中,与数据库进行交互通常需要使用数据库连接库。这些库允许你在C++程序中执行SQL查询并处理结果。以下是一些常见的数据库连接库和交互方式:

MySQL: 使用MySQL Connector/C++库进行交互。
#include<iostream>#include<mysqlx/xdevapi.h>int main() {    const std::string url = "mysqlx://user:password@localhost";    mysqlx::Session session(url);    mysqlx::Schema schema = session.getSchema("test");    mysqlx::Table table = schema.getTable("sample_table");    // 插入数据    table.insert("name", "age")        .values("Alice", 25)        .execute();    // 查询数据    mysqlx::RowResult result = table.select().execute();    for (const auto &row : result) {        std::cout<< row[0].get<std::string>() << ", "<< row[1].get<int>()<< std::endl;    }    return 0;}
PostgreSQL: 使用libpq库进行交互。
#include<iostream>#include <libpq-fe.h>int main() {    const char *conninfo = "dbname=test user=postgres password=secret hostaddr=127.0.0.1 port=5432";    PGconn *conn = PQconnectdb(conninfo);    if (PQstatus(conn) != CONNECTION_OK) {        std::cerr << "Connection to database failed: " << PQerrorMessage(conn)<< std::endl;        PQfinish(conn);        return 1;    }    // 执行查询    PGresult *res = PQexec(conn, "SELECT name, age FROM sample_table");    if (PQresultStatus(res) != PGRES_TUPLES_OK) {        std::cerr << "Query failed: " << PQerrorMessage(conn)<< std::endl;        PQclear(res);        PQfinish(conn);        return 1;    }    // 处理结果    int rows = PQntuples(res);    for (int i = 0; i< rows; ++i) {        std::cout << PQgetvalue(res, i, 0) << ", " << PQgetvalue(res, i, 1)<< std::endl;    }    PQclear(res);    PQfinish(conn);    return 0;}
SQLite: 使用SQLite C++库(如sqlite_modern_cpp)进行交互。
#include<iostream>#include<sqlite_modern_cpp.h>int main() {    sqlite::database db("test.db");    // 创建表    db << "CREATE TABLE IF NOT EXISTS sample_table (name TEXT, age INTEGER);";    // 插入数据    db << "INSERT INTO sample_table (name, age) VALUES (?, ?);"       << "Alice"       << 25;    // 查询数据    db << "SELECT name, age FROM sample_table;" >> [&](const std::string &name, int age) {        std::cout<< name << ", "<< age<< std::endl;    };    return 0;}

请注意,这些示例仅展示了基本的数据库操作。实际应用中,你可能需要处理更复杂的查询和事务。同时,确保正确处理错误和异常。

 
举报打赏
 
更多>同类物流大全
推荐图文
推荐物流大全
点击排行

网站首页  |  关于我们  |  联系方式网站留言    |  赣ICP备2021007278号