Ubuntu如何使用C++进行数据库操作

497
2025/4/10 9:33:15
栏目: 编程语言
开发者测试专用服务器限时活动,0元免费领,库存有限,领完即止! 点击查看>>

在Ubuntu上使用C++进行数据库操作,通常需要借助第三方库。以下是一些常用的数据库和相应的C++库:

  1. MySQL:可以使用MySQL Connector/C++库进行操作。首先安装库:
sudo apt-get install libmysqlcppconn-dev

然后创建一个简单的C++程序来连接和操作数据库:

#include <iostream>
#include <mysqlx/xdevapi.h>

using namespace std;
using namespace mysqlx;

int main() {
    try {
        Session session("localhost", 33060, "username", "password");
        Schema schema = session.getSchema("test");
        Table table = schema.getTable("users");

        // 插入数据
        table.insert("John", "Doe").execute();

        // 查询数据
        RowResult result = table.select("firstName", "lastName").execute();
        for (const Row &row : result) {
            cout << row[0] << " " << row[1] << endl;
        }

        // 更新数据
        table.update("John", "Doe").set("lastName", "Smith").execute();

        // 删除数据
        table.deleteRow("John", "Smith").execute();

        session.close();
    } catch (const Error &e) {
        cerr << "Error: " << e.what() << endl;
        return EXIT_FAILURE;
    }

    return EXIT_SUCCESS;
}

编译并运行程序:

g++ -o myapp myapp.cpp -lmysqlcppconn
./myapp
  1. PostgreSQL:可以使用libpqxx库进行操作。首先安装库:
sudo apt-get install libpqxx-dev

然后创建一个简单的C++程序来连接和操作数据库:

#include <iostream>
#include <pqxx/pqxx>

using namespace std;
using namespace pqxx;

int main() {
    try {
        connection conn("dbname=mydb user=myuser password=mypassword hostaddr=127.0.0.1 port=5432");
        if (conn.is_open()) {
            cout << "Connected to database successfully!" << endl;

            work txn(conn);

            // 插入数据
            txn.exec("INSERT INTO users (first_name, last_name) VALUES ('John', 'Doe')");

            // 查询数据
            result res = txn.exec("SELECT first_name, last_name FROM users");
            for (auto row : res) {
                cout << row[0].as<string>() << " " << row[1].as<string>() << endl;
            }

            // 更新数据
            txn.exec("UPDATE users SET last_name='Smith' WHERE first_name='John'");

            // 删除数据
            txn.exec("DELETE FROM users WHERE first_name='John' AND last_name='Smith'");

            txn.commit();
        } else {
            cerr << "Cannot open database" << endl;
            return EXIT_FAILURE;
        }
    } catch (const exception &e) {
        cerr << "Error: " << e.what() << endl;
        return EXIT_FAILURE;
    }

    return EXIT_SUCCESS;
}

编译并运行程序:

g++ -o myapp myapp.cpp -lpqxx -lpq
./myapp

注意:请根据实际情况替换数据库名称、用户名、密码和表结构。

辰迅云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>

推荐阅读: Ubuntu Opera 默认浏览器安装与设置方法