English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
이 튜토리얼은 libpqxx 라이브러리를 사용하며, 이는 PostgreSQL의 공식 C 인터페이스입니다. ++고객 API. libpqxx의 소스 코드는 BSD 라이선스 하에 제공되며, 따라서 무료로 다운로드할 수 있으며, 다른 사람에게 전달하고, 변경하고, 판매하고, 자신의 코드에 포함하고, 선택한 사람들과 공유할 수 있습니다.
최신 버전의 libpqxx는 libpqxx 다운로드 링크에서 다운로드할 수 있습니다(Libpqxx 다운로드)에 따라, 최신 버전을 다운로드하고 다음 단계로 이어집니다.-
wget http://pqxx.org/download/software/libpqxx/libpqxx-4.0.tar.gz tar xvfz libpqxx-4.0.tar.gz cd libpqxx-4.0 ./configure make make install
C를 시작하기 전에 / C ++ PostgreSQL 인터페이스를 사용하기 전에, PostgreSQL 설치 디렉토리에서 pg_hba.conf 파일을 찾아 다음 행을 추가하세요-
# IPv4 local connections: host all all 127.0.0.1/32 md5
postgres 서버가 실행되지 않는다면 다음 명령어로 시작할 수 있습니다./postgres 서버를 재시작합니다.-
[root@host]# service postgresql restart Stopping postgresql service: [ OK ] Starting postgresql service: [ OK ]
아래는 중요한 인터페이스 예제로, C에서 필요한 기능을 충족시킵니다./C++PostgreSQL 데이터베이스를 사용하는 요구 사항이 있습니다. 더 복잡한 애플리케이션을 찾고 계신다면 libpqxx 공식 문서를 확인하거나 상업적으로 사용할 수 있는 API를 사용할 수 있습니다.
S. No. | API & 설명 |
---|---|
1 | pqxx::connection C( const std::string & dbstring ) 이는 데이터베이스에 연결하는 데 사용할 typedef입니다. 여기서 dbstring은 데이터베이스에 연결하기 위한 파라미터를 제공합니다. 예를 들어: dbname = testdb user = postgres password=pass123 hostaddr=127.0.0.1 port=5432. 연결이 성공적으로 수립되면, C와 연결 객체가 생성되고, 다양한 유용한 공개 함수를 제공합니다. |
2 | C.is_open() is_open()는 연결 객체의 공개 메서드로, 부울 값을 반환합니다. 연결이 활성화되어 있으면 true를, 그렇지 않으면 false를 반환합니다. |
3 | C.disconnect() 이 메서드는 열린 데이터베이스 연결을 해제하는 데 사용됩니다. |
4 | pqxx::work W( C ) 이는 거래 객체를 생성하고 거래 모드에서 SQL 문을 실행하는 데 사용할 typedef입니다. 거래 객체가 성공적으로 생성되면, 그것은 변수 W에 할당되고, 거래 객체와 관련된 공개 메서드에 접근하기 위해 사용됩니다. |
5 | W.exec(const std::string & sql) 거래 객체의 이 공개 메서드는 SQL 문을 실행하는 데 사용됩니다. |
6 | W.commit() 거래 객체의 이 공개 메서드는 거래를 커밋하는 데 사용됩니다. |
7 | W.abort() 거래 객체의 이 공개 메서드는 거래를 롤백하는 데 사용됩니다. |
8 | pqxx::nontransaction N( C ) 이는 비거래 객체를 생성하고 비거래 모드에서 SQL 문을 실행하는 데 사용할 typedef입니다. 거래 객체가 성공적으로 생성되면, 그것은 변수 N에 할당되고, 비거래 객체와 관련된 공개 메서드에 접근하기 위해 사용됩니다. |
9 | N.exec(const std::string & sql) 이 공개 메서드는 비거래 객체에서 SQL 문을 실행하고 결과 객체를 반환합니다. 이 결과 객체는 실제로는 모든 반환된 레코드를 저장한 interator입니다. |
아래의 C 코드 구간은 포트에 연결하는 방법을 보여줍니다.5432로컬 컴퓨터에서 실행 중인 기존 데이터베이스입니다. 여기서는 줄延续를 역추사로 나타냅니다.
#include <iostream> #include <pqxx/pqxx> using namespace std; using namespace pqxx; int main(int argc, char* argv[]) { try { connection C("dbname = testdb user = postgres password = cohondob \ hostaddr = 127.0.0.1 port = 5432"); if (C.is_open()) { cout << "Opened database successfully: " << C.dbname() << endl; } cout << "Can't open database" << endl; return 1; } C.disconnect(); } catch (const std::exception &e) { cerr << e.what() << std::endl; return 1; } }
지금, 위의 프로그램을 컴파일하고 실행하여 testdb 데이터베이스에 연결해 보겠습니다. 이 데이터베이스는 여러분의 모델에 이미 존재하며, postgres 사용자와 pass 비밀번호로 접근할 수 있습니다.123접근.
데이터베이스 설정을 사용하여 사용자 ID와 비밀번호를 설정할 수 있습니다. 접근을 유지하십시오.-lpqxx와-lpq의 주어진 순서! 그렇지 않으면, 연결기가 이름이 부족하다고 판단하고 "PQ"로 시작하는 함수를 사용합니다.
$g++ test.cpp -lpqxx -lpq $./a.out Opened database successfully: testdb
이전에 생성된 데이터베이스에서 테이블을 생성하는 데 사용될 C 코드 단편입니다-
#include <iostream> #include <pqxx/pqxx> using namespace std; using namespace pqxx; int main(int argc, char* argv[]) { char * sql; try { connection C("dbname = testdb user = postgres password = cohondob \ hostaddr = 127.0.0.1 port = 5432"); if (C.is_open()) { cout << "Opened database successfully: " << C.dbname() << endl; } cout << "Can't open database" << endl; return 1; } /* SQL 생성 문장 */ sql = "CREATE TABLE COMPANY(" \ "ID INT PRIMARY KEY NOT NULL," \ "NAME TEXT NOT NULL," \ "AGE INT NOT NULL," \ "ADDRESS CHAR(50)," \ "SALARY REAL );"; /* 트랜잭션 객체 생성. */ work W(C); /* SQL 쿼리 실행 */ W.exec(sql); W.commit(); cout << "Table created successfully" << endl; C.disconnect(); } catch (const std::exception &e) { cerr << e.what() << std::endl; return 1; } return 0; }
위의 주어진 프로그램을 컴파일하고 실행하면 testdb 데이터베이스에 COMPANY 테이블을 생성하고 다음 문장을 표시합니다-
Opened database successfully: testdb Table created successfully
위의 예제에서 생성된 company 테이블에 기록을 생성하는 방법을 보여주는 C 코드 단편입니다-
#include <iostream> #include <pqxx/pqxx> using namespace std; using namespace pqxx; int main(int argc, char* argv[]) { char * sql; try { connection C("dbname = testdb user = postgres password = cohondob \ hostaddr = 127.0.0.1 port = 5432"); if (C.is_open()) { cout << "Opened database successfully: " << C.dbname() << endl; } cout << "Can't open database" << endl; return 1; } /* SQL 문 생성 */ sql = "INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY) "\ "VALUES (1, 'Paul', 32, 'California', 20000.00 ); "\ "INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY) "\ "VALUES (2, 'Allen', 25, 'Texas', 15000.00 ); "\ "INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY)" \ "VALUES (3, 'Teddy', 23, 'Norway', 20000.00 );" \ "INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY)" \ "VALUES (4, 'Mark', 25, 'Rich-Mond ', 65000.00 );"; /* 트랜잭션 객체 생성. */ work W(C); /* SQL 쿼리 실행 */ W.exec(sql); W.commit(); cout << "Records created successfully" << endl; C.disconnect(); } catch (const std::exception &e) { cerr << e.what() << std::endl; return 1; } return 0; }
위의 프로그램을 컴파일하고 실행하면 COMPANY 테이블에 주어진 기록을 생성하고 다음 두 행을 표시합니다-
Opened database successfully: testdb Records created successfully
아래의 C 코드 단락은 위의 예제에서 생성된 COMPANY 테이블에서 레코드를 가져오고 표시하는 방법을 보여줍니다
#include <iostream> #include <pqxx/pqxx> using namespace std; using namespace pqxx; int main(int argc, char* argv[]) { char * sql; try { connection C("dbname = testdb user = postgres password = cohondob \ hostaddr = 127.0.0.1 port = 5432"); if (C.is_open()) { cout << "Opened database successfully: " << C.dbname() << endl; } cout << "Can't open database" << endl; return 1; } /* SQL 문 생성 */ sql = "SELECT * from COMPANY"; /* 비트랜잭션 객체 생성. */ nontransaction N(C); /* SQL 쿼리 실행 */ result R(N.exec(sql)); /* 모든 기록을 나열합니다 */ for (result::const_iterator c = R.begin(); c != R.end(); ++c) { cout << "ID = " << c[0].as<int>() << endl; cout << "Name = " << c[1].as<string>() << endl; cout << "Age = " << c[2].as<int>() << endl; cout << "Address = " << c[3].as<string>() << endl; cout << "Salary = " << c[4].as<float>() << endl; } cout << "Operation done successfully" << endl; C.disconnect(); } catch (const std::exception &e) { cerr << e.what() << std::endl; return 1; } return 0; }
위의 주어진 프로그램을 컴파일하고 실행하면 다음과 같은 결과가 생성됩니다-
Opened database successfully: testdb ID = 1 Name = Paul Age = 32 Address = California Salary = 20000 ID = 2 Name = Allen Age = 25 Address = Texas Salary = 15000 ID = 3 Name = Teddy Age = 23 Address = Norway Salary = 20000 ID = 4 Name = Mark Age = 25 Address = Rich-Mond Salary = 65000 Operation done successfully
아래의 C 코드 단락은 UPDATE 문을 사용하여 어떤 레코드를 업데이트하고 COMPANY 테이블에서-업데이트된 레코드 가져오고 표시
#include <iostream> #include <pqxx/pqxx> using namespace std; using namespace pqxx; int main(int argc, char* argv[]) { char * sql; try { connection C("dbname = testdb user = postgres password = cohondob \ hostaddr = 127.0.0.1 port = 5432"); if (C.is_open()) { cout << "Opened database successfully: " << C.dbname() << endl; } cout << "Can't open database" << endl; return 1; } /* 트랜잭션 객체 생성. */ work W(C); /* SQL UPDATE 문 생성 */ sql = "UPDATE COMPANY set SALARY =" 25000.00 where ID=1"; /* SQL 쿼리 실행 */ W.exec(sql); W.commit(); cout << "Records updated successfully" << endl; /* SQL SELECT 문 생성 */ sql = "SELECT * from COMPANY"; /* 비트랜잭션 객체 생성. */ nontransaction N(C); /* SQL 쿼리 실행 */ result R(N.exec(sql)); /* 모든 기록을 나열합니다 */ for (result::const_iterator c = R.begin(); c != R.end(); ++c) { cout << "ID = " << c[0].as<int>() << endl; cout << "Name = " << c[1].as<string>() << endl; cout << "Age = " << c[2].as<int>() << endl; cout << "Address = " << c[3].as<string>() << endl; cout << "Salary = " << c[4].as<float>() << endl; } cout << "Operation done successfully" << endl; C.disconnect(); } catch (const std::exception &e) { cerr << e.what() << std::endl; return 1; } return 0; }
위의 프로그램이 컴파일되고 실행될 때, 다음과 같은 결과가 생성됩니다-
Opened database successfully: testdb Records updated successfully ID = 2 Name = Allen Age = 25 Address = Texas Salary = 15000 ID = 3 Name = Teddy Age = 23 Address = Norway Salary = 20000 ID = 4 Name = Mark Age = 25 Address = Rich-Mond Salary = 65000 ID = 1 Name = Paul Age = 32 Address = California Salary = 25000 Operation done successfully
아래의 C 코드 단락은 DELETE 문을 사용하여 어떤 레코드를 지우고 COMPANY 테이블에서-기존의 레코드를 가져오고 표시
#include <iostream> #include <pqxx/pqxx> using namespace std; using namespace pqxx; int main(int argc, char* argv[]) { char * sql; try { connection C("dbname = testdb user = postgres password = cohondob \ hostaddr = 127.0.0.1 port = 5432"); if (C.is_open()) { cout << "Opened database successfully: " << C.dbname() << endl; } cout << "Can't open database" << endl; return 1; } /* 트랜잭션 객체 생성. */ work W(C); /* SQL DELETE 문 생성 */ sql = "DELETE from COMPANY where ID =" 2"; /* SQL 쿼리 실행 */ W.exec(sql); W.commit(); cout << "Records deleted successfully" << endl; /* SQL SELECT 문 생성 */ sql = "SELECT * from COMPANY"; /* 비트랜잭션 객체 생성. */ nontransaction N(C); /* SQL 쿼리 실행 */ result R(N.exec(sql)); /* 모든 기록을 나열합니다 */ for (result::const_iterator c = R.begin(); c != R.end(); ++c) { cout << "ID = " << c[0].as<int>() << endl; cout << "Name = " << c[1].as<string>() << endl; cout << "Age = " << c[2].as<int>() << endl; cout << "Address = " << c[3].as<string>() << endl; cout << "Salary = " << c[4].as<float>() << endl; } cout << "Operation done successfully" << endl; C.disconnect(); } catch (const std::exception &e) { cerr << e.what() << std::endl; return 1; } return 0; }
위의 주어진 프로그램을 컴파일하고 실행하면 다음과 같은 결과가 생성됩니다-
Opened database successfully: testdb Records deleted successfully ID = 3 Name = Teddy Age = 23 Address = Norway Salary = 20000 ID = 4 Name = Mark Age = 25 Address = Rich-Mond Salary = 65000 ID = 1 Name = Paul Age = 32 Address = California Salary = 25000 Operation done successfully