如何与libpqxx API同时插入数据? (PostgreSQL,线程)

时间:2019-07-28 21:21:54

标签: c++ sql postgresql libpqxx

使用的东西:

libray:libpqxx:x64-windows版本6.4.4

操作系统:Windows 10

编译器:Visual C ++(MSVC)

这是我的SQL表

CREATE TABLE test(
    test_name VARCHAR(16)
);

这是我的简约测试版本。

main.cpp

#include <pqxx/pqxx> 
#include "test.h"
int main()
{

    pqxx::connection database_connection("dbname = test user = postgres password = *****\
      hostaddr = 127.0.0.1 port = 5432");


    database_connection.prepare("insert_into_table", "INSERT INTO test \
    VALUES ($1)");

    test test(&database_connection);

    system("pause");
}

test.h

#pragma once
#include <pqxx/connection.hxx>
#include <thread>
#include <array>
class test
{
public:
    explicit test(pqxx::connection* database_connection);
    void InsertData();

    std::array<std::thread, 1> threads{};
    pqxx::connection* database_connection;
};

test.cpp

#include "test.h"
#include <iostream>
#include <pqxx/transaction.hxx>

test::test(pqxx::connection* database_connection) : database_connection(database_connection)
{
    for (auto& i : threads)
    {
        i = std::thread(&test::InsertData, this);
    }
}


void test::InsertData()
{

    pqxx::work work(*database_connection);
    try
    {

        pqxx::result result = work.exec_prepared("insert_into_table", "test_data"); //prepared data in real project pqxx::binarystring blobs

        work.commit();

    }
    catch (const std::exception& e) {
        work.abort();
    }

}

将test.h中的线程大小更改为大于1的任何值。

注意:我必须使用准备好的SQL语句,以后才能将原始的teatea数据插入到我的表中。

输出:

        Exception thrown at 0x00007FFC2FF44008 in Project3.exe: Microsoft C++ exception : pqxx::usage_error at memory location 0x000000CEB00FF050.
        Exception thrown at 0x00007FFC2FF44008 in Project3.exe: Microsoft C++ exception : pqxx::usage_error at memory location 0x000000CEB03FEF50.
        Exception thrown at 0x00007FFC2FF44008 in Project3.exe: Microsoft C++ exception : pqxx::usage_error at memory location 0x000000CEB04FED30.
        Exception thrown at 0x00007FFC2FF44008 in Project3.exe: Microsoft C++ exception : pqxx::usage_error at memory location 0x000000CEB02FEAF0.
        Debug Error!

如何与此API并发插入。

1 个答案:

答案 0 :(得分:1)

解决方案链接:https://pqxx.org/development/libpqxx/wiki/Threading

就我而言,我将连接更改为

static thread_local database_connection;

因此每个线程都有自己的连接,然后代码可以正常工作而没有太大变化。