溫馨提示×

Ubuntu如何使用C++進行數據庫操作

小樊
82
2025-04-10 07:26:54
欄目: 編程語言

在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

注意:請根據實際情況替換數據庫名稱、用戶名、密碼和表結構。

0
亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女