温馨提示×

CentOS C++数据库连接怎么写

小樊
41
2025-10-07 02:01:15
栏目: 编程语言

在CentOS上使用C++连接数据库,通常会选择MySQL或PostgreSQL等流行的关系型数据库。以下是使用C++连接MySQL和PostgreSQL数据库的基本步骤和示例代码。

连接MySQL数据库

  1. 安装MySQL客户端库

    sudo yum install mysql-devel
    
  2. 编写C++代码: 使用MySQL提供的C API来连接数据库。

    #include <mysql/mysql.h>
    #include <iostream>
    
    int main() {
        MYSQL *conn;
        MYSQL_RES *res;
        MYSQL_ROW row;
    
        // 初始化连接
        conn = mysql_init(NULL);
    
        // 连接到数据库
        if (!mysql_real_connect(conn, "localhost", "user", "password", "database", 3306, NULL, 0)) {
            fprintf(stderr, "%s\n", mysql_error(conn));
            exit(1);
        }
    
        // 执行查询
        if (mysql_query(conn, "SELECT * FROM table_name")) {
            fprintf(stderr, "%s\n", mysql_error(conn));
            exit(1);
        }
    
        // 获取结果集
        res = mysql_store_result(conn);
    
        // 遍历结果集
        while ((row = mysql_fetch_row(res)) != NULL) {
            std::cout << row[0] << " " << row[1] << std::endl;
        }
    
        // 释放资源
        mysql_free_result(res);
        mysql_close(conn);
    
        return 0;
    }
    
  3. 编译代码

    g++ -o mysql_example mysql_example.cpp -lmysqlclient
    
  4. 运行程序

    ./mysql_example
    

连接PostgreSQL数据库

  1. 安装PostgreSQL客户端库

    sudo yum install postgresql-devel
    
  2. 编写C++代码: 使用libpqxx库来连接数据库。首先需要安装libpqxx库:

    sudo yum install libpqxx-devel
    

    然后编写C++代码:

    #include <pqxx/pqxx>
    #include <iostream>
    
    int main() {
        try {
            // 连接到数据库
            pqxx::connection C("dbname=database user=user password=password hostaddr=127.0.0.1 port=5432");
    
            // 创建一个非事务对象
            pqxx::nontransaction N(C);
    
            // 执行查询
            pqxx::result R = N.exec("SELECT * FROM table_name");
    
            // 遍历结果集
            for (auto row : R) {
                std::cout << row[0].as<std::string>() << " " << row[1].as<std::string>() << std::endl;
            }
        } catch (const std::exception &e) {
            std::cerr << e.what() << std::endl;
            return 1;
        }
    
        return 0;
    }
    
  3. 编译代码

    g++ -o pgsql_example pgsql_example.cpp -lpqxx -lpq
    
  4. 运行程序

    ./pgsql_example
    

以上是连接MySQL和PostgreSQL数据库的基本步骤和示例代码。根据具体需求,可能需要调整数据库连接参数、查询语句和错误处理逻辑。

0