Python PostgreSQL-빠른 가이드

PostgreSQL은 강력한 오픈 소스 객체 관계형 데이터베이스 시스템입니다. 15 년 이상의 활발한 개발 단계와 신뢰성, 데이터 무결성 및 정확성에 대한 강력한 명성을 얻은 입증 된 아키텍처를 보유하고 있습니다.

Python을 사용하여 PostgreSQL과 통신하려면 Python 프로그래밍 용으로 제공되는 어댑터 인 psycopg를 설치해야합니다. 현재 버전은 다음과 같습니다. psycog2.

psycopg2는 매우 작고 빠르며 바위처럼 안정적이라는 목표로 작성되었습니다. PIP (python의 패키지 관리자)에서 사용할 수 있습니다.

PIP를 사용하여 Psycog2 설치

우선, 파이썬과 PIP가 시스템에 제대로 설치되어 있고 PIP가 최신 상태인지 확인하십시오.

PIP를 업그레이드하려면 명령 프롬프트를 열고 다음 명령을 실행하십시오.

C:\Users\Tutorialspoint>python -m pip install --upgrade pip
Collecting pip
   Using cached 
https://files.pythonhosted.org/packages/8d/07/f7d7ced2f97ca3098c16565efbe6b15fafcba53e8d9bdb431e09140514b0/pip-19.2.2-py2.py3-none-any.whl
Installing collected packages: pip
   Found existing installation: pip 19.0.3
      Uninstalling pip-19.0.3:
         Successfully uninstalled pip-19.0.3
Successfully installed pip-19.2.2

그런 다음 관리자 모드에서 명령 프롬프트를 열고 pip install psycopg2-binary 아래와 같이 명령-

C:\WINDOWS\system32>pip install psycopg2-binary
Collecting psycopg2-binary
   Using cached 
https://files.pythonhosted.org/packages/80/79/d0d13ce4c2f1addf4786f4a2ded802c2df66ddf3c1b1a982ed8d4cb9fc6d/psycopg2_binary-2.8.3-cp37-cp37m-win32.whl
Installing collected packages: psycopg2-binary
Successfully installed psycopg2-binary-2.8.3

확인

설치를 확인하려면 다음 줄이 포함 된 샘플 Python 스크립트를 만듭니다.

import mysql.connector

설치가 성공하면 실행하면 오류가 발생하지 않습니다.

D:\Python_PostgreSQL>import psycopg2
D:\Python_PostgreSQL>

PostgreSQL은 쿼리를 실행하기위한 자체 셸을 제공합니다. PostgreSQL 데이터베이스와의 연결을 설정하려면 시스템에 올바르게 설치했는지 확인하십시오. PostgreSQL 셸 프롬프트를 열고 서버, 데이터베이스, 사용자 이름 및 암호와 같은 세부 정보를 전달합니다. 제공 한 모든 세부 정보가 적절하다면 PostgreSQL 데이터베이스와의 연결이 설정됩니다.

세부 정보를 전달하는 동안 기본 서버, 데이터베이스, 포트 및 셸에서 제안한 사용자 이름을 사용할 수 있습니다.

Python을 사용하여 연결 설정

연결 클래스 psycopg2연결 인스턴스를 나타내거나 처리합니다. 다음을 사용하여 새 연결을 만들 수 있습니다.connect()함수. 이것은 dbname, user, password, host, port와 같은 기본 연결 매개 변수를 받아들이고 연결 개체를 반환합니다. 이 기능을 사용하여 PostgreSQL과의 연결을 설정할 수 있습니다.

예

다음 Python 코드는 기존 데이터베이스에 연결하는 방법을 보여줍니다. 데이터베이스가 존재하지 않으면 생성되고 마지막으로 데이터베이스 개체가 반환됩니다. PostgreSQL의 기본 데이터베이스 이름은 postrgre입니다. 따라서 데이터베이스 이름으로 제공합니다.

import psycopg2
#establishing the connection
conn = psycopg2.connect(
   database="postgres", user='postgres', password='password', 
   host='127.0.0.1', port= '5432'
)

#Creating a cursor object using the cursor() method
cursor = conn.cursor()

#Executing an MYSQL function using the execute() method
cursor.execute("select version()")

#Fetch a single row using fetchone() method.
data = cursor.fetchone()
print("Connection established to: ",data)

#Closing the connection
conn.close()
Connection established to: (
   'PostgreSQL 11.5, compiled by Visual C++ build 1914, 64-bit',
)

산출

Connection established to: (
   'PostgreSQL 11.5, compiled by Visual C++ build 1914, 64-bit',
)

CREATE DATABASE 문을 사용하여 PostgreSQL에서 데이터베이스를 생성 할 수 있습니다. 명령 뒤에 생성 할 데이터베이스의 이름을 지정하여 PostgreSQL 셸 프롬프트에서이 문을 실행할 수 있습니다.

통사론

다음은 CREATE DATABASE 문의 구문입니다.

CREATE DATABASE dbname;

예

다음 문은 PostgreSQL에서 testdb라는 데이터베이스를 생성합니다.

postgres=# CREATE DATABASE testdb;
CREATE DATABASE

\ l 명령을 사용하여 PostgreSQL에서 데이터베이스를 나열 할 수 있습니다. 데이터베이스 목록을 확인하면 다음과 같이 새로 생성 된 데이터베이스를 찾을 수 있습니다.

postgres=# \l
                                                List of databases
   Name    | Owner    | Encoding |        Collate             |     Ctype   |
-----------+----------+----------+----------------------------+-------------+
mydb       | postgres | UTF8     | English_United States.1252 | ........... |
postgres   | postgres | UTF8     | English_United States.1252 | ........... |
template0  | postgres | UTF8     | English_United States.1252 | ........... |
template1  | postgres | UTF8     | English_United States.1252 | ........... |
testdb     | postgres | UTF8     | English_United States.1252 | ........... |
(5 rows)

SQL 문 CREATE DATABASE를 둘러싼 래퍼 인 createdb 명령을 사용하여 명령 프롬프트에서 PostgreSQL에 데이터베이스를 생성 할 수도 있습니다 .

C:\Program Files\PostgreSQL\11\bin> createdb -h localhost -p 5432 -U postgres sampledb
Password:

Python을 사용하여 데이터베이스 생성

psycopg2의 커서 클래스는 다양한 PostgreSQL 명령을 실행하고 레코드를 가져오고 데이터를 복사하는 다양한 방법을 제공합니다. Connection 클래스의 cursor () 메서드를 사용하여 커서 객체를 만들 수 있습니다.

이 클래스의 execute () 메서드는 PostgreSQL 쿼리를 매개 변수로 받아 실행합니다.

따라서 PostgreSQL에서 데이터베이스를 생성하려면이 방법을 사용하여 CREATE DATABASE 쿼리를 실행합니다.

예

다음 Python 예제는 PostgreSQL 데이터베이스에 mydb라는 데이터베이스를 생성합니다.

import psycopg2

#establishing the connection

conn = psycopg2.connect(
   database="postgres", user='postgres', password='password', 
   host='127.0.0.1', port= '5432'
)
conn.autocommit = True

#Creating a cursor object using the cursor() method
cursor = conn.cursor()

#Preparing query to create a database
sql = '''CREATE database mydb''';

#Creating a database
cursor.execute(sql)
print("Database created successfully........")

#Closing the connection
conn.close()

산출

Database created successfully........

CREATE TABLE 문을 사용하여 PostgreSQL의 데이터베이스에 새 테이블을 만들 수 있습니다. 이를 실행하는 동안 테이블 이름, 열 이름 및 해당 데이터 유형을 지정해야합니다.

통사론

다음은 PostgreSQL의 CREATE TABLE 문의 구문입니다.

CREATE TABLE table_name(
   column1 datatype,
   column2 datatype,
   column3 datatype,
   .....
   columnN datatype,
);

예

다음 예제는 PostgreSQL에서 이름이 CRICKETERS 인 테이블을 생성합니다.

postgres=# CREATE TABLE CRICKETERS (
   First_Name VARCHAR(255),
   Last_Name VARCHAR(255),
   Age INT,
   Place_Of_Birth VARCHAR(255),
   Country VARCHAR(255));
CREATE TABLE
postgres=#

\ dt 명령을 사용하여 PostgreSQL의 데이터베이스에있는 테이블 목록을 가져올 수 있습니다. 테이블 생성 후 테이블 목록을 확인할 수 있다면 새로 생성 된 테이블을 다음과 같이 관찰 할 수 있습니다.

postgres=# \dt
         List of relations
Schema  | Name       | Type  | Owner
--------+------------+-------+----------
public  | cricketers | table | postgres
(1 row)
postgres=#

같은 방법으로 아래와 같이 \ d를 사용하여 생성 된 테이블에 대한 설명을 얻을 수 있습니다.

postgres=# \d cricketers
                        Table "public.cricketers"
Column          | Type                   | Collation | Nullable | Default
----------------+------------------------+-----------+----------+---------
first_name      | character varying(255) |           |          |
last_name       | character varying(255) |           |          |
age             | integer                |           |          |
place_of_birth  | character varying(255) |           |          |
country         | character varying(255) |           |          |

postgres=#

Python을 사용하여 테이블 생성

Python을 사용하여 테이블을 생성하려면 pyscopg2 Cursor의 execute () 메서드를 사용하여 CREATE TABLE 문을 실행해야합니다 .

예

다음 Python 예제에서는 이름이 employee 인 테이블을 만듭니다.

import psycopg2

#Establishing the connection

conn = psycopg2.connect(
   database="mydb", user='postgres', password='password', host='127.0.0.1', port= '5432'
)

#Creating a cursor object using the cursor() method
cursor = conn.cursor()

#Doping EMPLOYEE table if already exists.
cursor.execute("DROP TABLE IF EXISTS EMPLOYEE")

#Creating table as per requirement
sql ='''CREATE TABLE EMPLOYEE(
   FIRST_NAME CHAR(20) NOT NULL,
   LAST_NAME CHAR(20),
   AGE INT,
   SEX CHAR(1),
   INCOME FLOAT)'''
cursor.execute(sql)
print("Table created successfully........")

#Closing the connection
conn.close()

산출

Table created successfully........

PostgreSQL의 기존 테이블에 레코드를 삽입 할 수 있습니다. INSERT INTO성명서. 이를 실행하는 동안 테이블의 이름과 테이블의 열 값을 지정해야합니다.

통사론

다음은 INSERT 문의 권장 구문입니다-

INSERT INTO TABLE_NAME (column1, column2, column3,...columnN)
VALUES (value1, value2, value3,...valueN);

여기서 column1, column2, column3, ..은 테이블의 열 이름이고 value1, value2, value3, ...은 테이블에 삽입해야하는 값입니다.

예

아래와 같이 CREATE TABLE 문을 사용하여 CRICKETERS라는 이름의 테이블을 만들었다 고 가정합니다.

postgres=# CREATE TABLE CRICKETERS (
   First_Name VARCHAR(255),
   Last_Name VARCHAR(255),
   Age INT,
   Place_Of_Birth VARCHAR(255),
   Country VARCHAR(255)
);
CREATE TABLE
postgres=#

다음 PostgreSQL 문은 위에서 생성 된 테이블에 행을 삽입합니다-

postgres=# insert into CRICKETERS 
   (First_Name, Last_Name, Age, Place_Of_Birth, Country) values
   ('Shikhar', 'Dhawan', 33, 'Delhi', 'India');
INSERT 0 1
postgres=#

INSERT INTO 문을 사용하여 레코드를 삽입하는 동안 열 이름을 건너 뛰면 레코드가 삽입되고 건너 뛴 열에 빈 공간이 남습니다.

postgres=# insert into CRICKETERS 
   (First_Name, Last_Name, Country) values('Jonathan', 'Trott', 'SouthAfrica');
INSERT 0 1

전달하는 값의 순서가 테이블의 각 열 이름과 동일한 경우 열 이름을 지정하지 않고 테이블에 레코드를 삽입 할 수도 있습니다.

postgres=# insert into CRICKETERS values('Kumara', 'Sangakkara', 41, 'Matale', 'Srilanka');
INSERT 0 1
postgres=# insert into CRICKETERS values('Virat', 'Kohli', 30, 'Delhi', 'India');
INSERT 0 1
postgres=# insert into CRICKETERS values('Rohit', 'Sharma', 32, 'Nagpur', 'India');
INSERT 0 1
postgres=#

테이블에 레코드를 삽입 한 후 아래와 같이 SELECT 문을 사용하여 내용을 확인할 수 있습니다.

postgres=# SELECT * from CRICKETERS;
 first_name | last_name  | age | place_of_birth | country
------------+------------+-----+----------------+-------------
Shikhar     | Dhawan     | 33  | Delhi          | India
Jonathan    | Trott      |     |                | SouthAfrica
Kumara      | Sangakkara | 41  | Matale         | Srilanka
Virat       | Kohli      | 30  | Delhi          | India
Rohit       | Sharma     | 32  | Nagpur         | India
(5 rows)

Python을 사용하여 데이터 삽입

psycopg2의 커서 클래스는 execute () 메서드라는 이름의 메서드를 제공합니다. 이 메서드는 쿼리를 매개 변수로 받아들이고 실행합니다.

따라서 Python을 사용하여 PostgreSQL의 테이블에 데이터를 삽입하려면-

  • 수입 psycopg2 꾸러미.

  • 다음을 사용하여 연결 개체를 만듭니다. connect() 사용자 이름, 암호, 호스트 (선택적 기본값 : localhost) 및 데이터베이스 (선택적)를 매개 변수로 전달합니다.

  • 속성 값으로 false를 설정하여 자동 커미트 모드를 끄십시오. autocommit.

  • 그만큼 cursor() 의 방법 Connectionpsycopg2 라이브러리의 클래스는 커서 객체를 반환합니다. 이 메서드를 사용하여 커서 개체를 만듭니다.

  • 그런 다음 INSERT 문을 execute () 메서드에 매개 변수로 전달하여 실행합니다.

예

다음 Python 프로그램은 PostgreSQL 데이터베이스에 EMPLOYEE라는 이름의 테이블을 생성하고 execute () 메서드를 사용하여 레코드를 삽입합니다.

import psycopg2

#Establishing the connection
conn = psycopg2.connect(
   database="mydb", user='postgres', password='password', host='127.0.0.1', port= '5432'
)

#Setting auto commit false
conn.autocommit = True

#Creating a cursor object using the cursor() method
cursor = conn.cursor()

# Preparing SQL queries to INSERT a record into the database.
cursor.execute('''INSERT INTO EMPLOYEE(FIRST_NAME, LAST_NAME, AGE, SEX, INCOME) 
   VALUES ('Ramya', 'Rama priya', 27, 'F', 9000)''')
cursor.execute('''INSERT INTO EMPLOYEE(FIRST_NAME, LAST_NAME, AGE, SEX, INCOME) 
   VALUES ('Vinay', 'Battacharya', 20, 'M', 6000)''')
cursor.execute('''INSERT INTO EMPLOYEE(FIRST_NAME, LAST_NAME, AGE, SEX, INCOME) 
   VALUES ('Sharukh', 'Sheik', 25, 'M', 8300)''')
cursor.execute('''INSERT INTO EMPLOYEE(FIRST_NAME, LAST_NAME, AGE, SEX, INCOME) 
   VALUES ('Sarmista', 'Sharma', 26, 'F', 10000)''')
cursor.execute('''INSERT INTO EMPLOYEE(FIRST_NAME, LAST_NAME, AGE, SEX, INCOME) 
   VALUES ('Tripthi', 'Mishra', 24, 'F', 6000)''')

# Commit your changes in the database
conn.commit()

print("Records inserted........")

# Closing the connection
conn.close()

산출

Records inserted........

SELECT 문을 사용하여 PostgreSQL에서 기존 테이블의 내용을 검색 할 수 있습니다. 이 명령문에서 테이블의 이름을 지정해야하며 결과 세트라고하는 테이블 형식으로 해당 컨텐츠를 리턴합니다.

통사론

다음은 PostgreSQL의 SELECT 문의 구문입니다.

SELECT column1, column2, columnN FROM table_name;

예

다음 쿼리를 사용하여 이름이 CRICKETERS 인 테이블을 생성했다고 가정합니다.

postgres=# CREATE TABLE CRICKETERS ( 
   First_Name VARCHAR(255), Last_Name VARCHAR(255), Age int, 
   Place_Of_Birth VARCHAR(255), Country VARCHAR(255)
);

CREATE TABLE

postgres=#

그리고 INSERT 문을 사용하여 5 개의 레코드를 삽입했다면-

postgres=# insert into CRICKETERS values('Shikhar', 'Dhawan', 33, 'Delhi', 'India');
INSERT 0 1
postgres=# insert into CRICKETERS values('Jonathan', 'Trott', 38, 'CapeTown', 'SouthAfrica');
INSERT 0 1
postgres=# insert into CRICKETERS values('Kumara', 'Sangakkara', 41, 'Matale', 'Srilanka');
INSERT 0 1
postgres=# insert into CRICKETERS values('Virat', 'Kohli', 30, 'Delhi', 'India');
INSERT 0 1
postgres=# insert into CRICKETERS values('Rohit', 'Sharma', 32, 'Nagpur', 'India');
INSERT 0 1

다음 SELECT 쿼리는 CRICKETERS 테이블에서 FIRST_NAME, LAST_NAME 및 COUNTRY 열의 값을 검색합니다.

postgres=# SELECT FIRST_NAME, LAST_NAME, COUNTRY FROM CRICKETERS;
 first_name | last_name  | country
------------+------------+-------------
Shikhar     | Dhawan     | India
Jonathan    | Trott      | SouthAfrica
Kumara      | Sangakkara | Srilanka
Virat       | Kohli      | India
Rohit       | Sharma     | India
(5 rows)

각 레코드의 모든 열을 검색하려면 아래와 같이 열 이름을 "⚹"로 바꿔야합니다.

postgres=# SELECT * FROM CRICKETERS;
first_name  | last_name  | age | place_of_birth | country
------------+------------+-----+----------------+-------------
Shikhar     | Dhawan     | 33  | Delhi          | India
Jonathan    | Trott      | 38  | CapeTown       | SouthAfrica
Kumara      | Sangakkara | 41  | Matale         | Srilanka
Virat       | Kohli      | 30  | Delhi          | India
Rohit       | Sharma     | 32  | Nagpur         | India
(5 rows)

postgres=#

Python을 사용하여 데이터 검색

모든 데이터베이스에 대한 읽기 작업은 데이터베이스에서 유용한 정보를 가져 오는 것을 의미합니다. psycopg2에서 제공하는 fetch () 메서드를 사용하여 PostgreSQL에서 데이터를 가져올 수 있습니다.

Cursor 클래스는 fetchall (), fetchmany () 및 fetchone ()의 세 가지 메소드를 제공합니다.

  • fetchall () 메서드는 쿼리 결과 집합의 모든 행을 검색하여 튜플 목록으로 반환합니다. (몇 개의 행을 검색 한 후 이것을 실행하면 나머지 행을 반환합니다).

  • fetchone () 메서드는 쿼리 결과에서 다음 행을 가져 와서 튜플로 반환합니다.

Note − 결과 집합은 커서 개체를 사용하여 테이블을 쿼리 할 때 반환되는 개체입니다.

예

다음 Python 프로그램은 PostgreSQL의 mydb라는 데이터베이스에 연결하고 EMPLOYEE라는 테이블에서 모든 레코드를 검색합니다.

import psycopg2

#establishing the connection
conn = psycopg2.connect(
   database="mydb", user='postgres', password='password', host='127.0.0.1', port= '5432'
)

#Setting auto commit false
conn.autocommit = True

#Creating a cursor object using the cursor() method
cursor = conn.cursor()

#Retrieving data
cursor.execute('''SELECT * from EMPLOYEE''')

#Fetching 1st row from the table
result = cursor.fetchone();
print(result)

#Fetching 1st row from the table
result = cursor.fetchall();
print(result)

#Commit your changes in the database
conn.commit()

#Closing the connection
conn.close()

산출

('Ramya', 'Rama priya', 27, 'F', 9000.0)
[
   ('Vinay', 'Battacharya', 20, 'M', 6000.0),
   ('Sharukh', 'Sheik', 25, 'M', 8300.0),
   ('Sarmista', 'Sharma', 26, 'F', 10000.0),
   ('Tripthi', 'Mishra', 24, 'F', 6000.0)
]

SELECT, UPDATE 또는 DELETE 작업을 수행하는 동안 WHERE 절을 사용하여 레코드를 필터링하는 조건을 지정할 수 있습니다. 작업은 주어진 조건을 만족하는 레코드에 대해 수행됩니다.

통사론

다음은 PostgreSQL의 WHERE 절 구문입니다.

SELECT column1, column2, columnN
FROM table_name
WHERE [search_condition]

비교 또는 논리 연산자를 사용하여 search_condition을 지정할 수 있습니다. >, <, =, LIKE, NOT 등. 다음 예제는이 개념을 명확하게합니다.

예

다음 쿼리를 사용하여 이름이 CRICKETERS 인 테이블을 생성했다고 가정합니다.

postgres=# CREATE TABLE CRICKETERS (
   First_Name VARCHAR(255), Last_Name VARCHAR(255), Age int, 
   Place_Of_Birth VARCHAR(255), Country VARCHAR(255)
);
CREATE TABLE
postgres=#

그리고 INSERT 문을 사용하여 5 개의 레코드를 삽입했다면-

postgres=# insert into CRICKETERS values('Shikhar', 'Dhawan', 33, 'Delhi', 'India');
INSERT 0 1
postgres=# insert into CRICKETERS values('Jonathan', 'Trott', 38, 'CapeTown', 'SouthAfrica');
INSERT 0 1
postgres=# insert into CRICKETERS values('Kumara', 'Sangakkara', 41, 'Matale', 'Srilanka');
INSERT 0 1
postgres=# insert into CRICKETERS values('Virat', 'Kohli', 30, 'Delhi', 'India');
INSERT 0 1
postgres=# insert into CRICKETERS values('Rohit', 'Sharma', 32, 'Nagpur', 'India');
INSERT 0 1

다음 SELECT 문은 나이가 35보다 큰 레코드를 검색합니다-

postgres=# SELECT * FROM CRICKETERS WHERE AGE > 35;
 first_name | last_name  | age | place_of_birth | country
------------+------------+-----+----------------+-------------
Jonathan    | Trott      | 38  | CapeTown       | SouthAfrica
Kumara      | Sangakkara | 41  | Matale         | Srilanka
(2 rows)

postgres=#

Python을 사용하는 Where 절

파이썬 프로그램을 사용하여 테이블에서 특정 레코드를 가져 오려면 WHERE 절이 있는 SELECT 문을 매개 변수로 전달하여execute() 방법.

예

다음 파이썬 예제는 파이썬을 사용하는 WHERE 명령의 사용법을 보여줍니다.

import psycopg2
#establishing the connection
conn = psycopg2.connect(
   database="mydb", user='postgres', password='password', host='127.0.0.1', port= '5432'
)

#Setting auto commit false
conn.autocommit = True

#Creating a cursor object using the cursor() method
cursor = conn.cursor()

#Doping EMPLOYEE table if already exists.
cursor.execute("DROP TABLE IF EXISTS EMPLOYEE")
sql = '''CREATE TABLE EMPLOYEE(
   FIRST_NAME CHAR(20) NOT NULL,
   LAST_NAME CHAR(20),
   AGE INT,
   SEX CHAR(1),
   INCOME FLOAT)'''
cursor.execute(sql)

#Populating the table
insert_stmt = "INSERT INTO EMPLOYEE 
   (FIRST_NAME, LAST_NAME, AGE, SEX, INCOME) VALUES (%s, %s, %s, %s, %s)"
data = [('Krishna', 'Sharma', 19, 'M', 2000), ('Raj', 'Kandukuri', 20, 'M', 7000),
   ('Ramya', 'Ramapriya', 25, 'M', 5000),('Mac', 'Mohan', 26, 'M', 2000)]
cursor.executemany(insert_stmt, data)

#Retrieving specific records using the where clause
cursor.execute("SELECT * from EMPLOYEE WHERE AGE <23")
print(cursor.fetchall())

#Commit your changes in the database
conn.commit()

#Closing the connection
conn.close()

산출

[('Krishna', 'Sharma', 19, 'M', 2000.0), ('Raj', 'Kandukuri', 20, 'M', 7000.0)]

일반적으로 테이블에서 데이터를 검색하려고하면 삽입 한 순서와 동일한 순서로 레코드를 가져옵니다.

사용 ORDER BY 절, 테이블의 레코드를 검색하는 동안 원하는 열을 기준으로 결과 레코드를 오름차순 또는 내림차순으로 정렬 할 수 있습니다.

통사론

다음은 PostgreSQL의 ORDER BY 절 구문입니다.

SELECT column-list
FROM table_name
[WHERE condition]
[ORDER BY column1, column2, .. columnN] [ASC | DESC];

예

다음 쿼리를 사용하여 이름이 CRICKETERS 인 테이블을 생성했다고 가정합니다.

postgres=# CREATE TABLE CRICKETERS (
   First_Name VARCHAR(255), Last_Name VARCHAR(255), Age int, 
   Place_Of_Birth VARCHAR(255), Country VARCHAR(255)
);
CREATE TABLE
postgres=#

그리고 INSERT 문을 사용하여 5 개의 레코드를 삽입했다면-

postgres=# insert into CRICKETERS values('Shikhar', 'Dhawan', 33, 'Delhi', 'India');
INSERT 0 1
postgres=# insert into CRICKETERS values('Jonathan', 'Trott', 38, 'CapeTown', 'SouthAfrica');
INSERT 0 1
postgres=# insert into CRICKETERS values('Kumara', 'Sangakkara', 41, 'Matale', 'Srilanka');
INSERT 0 1
postgres=# insert into CRICKETERS values('Virat', 'Kohli', 30, 'Delhi', 'India');
INSERT 0 1
postgres=# insert into CRICKETERS values('Rohit', 'Sharma', 32, 'Nagpur', 'India');
INSERT 0 1

다음 SELECT 문은 연령의 오름차순으로 CRICKETERS 테이블의 행을 검색합니다-

postgres=# SELECT * FROM CRICKETERS ORDER BY AGE;
 first_name | last_name  | age | place_of_birth | country
------------+------------+-----+----------------+-------------
Virat       | Kohli      | 30  | Delhi          | India
Rohit       | Sharma     | 32  | Nagpur         | India
Shikhar     | Dhawan     | 33  | Delhi          | India
Jonathan    | Trott      | 38  | CapeTown       | SouthAfrica
Kumara      | Sangakkara | 41  | Matale         | Srilanka
(5 rows)es:

둘 이상의 열을 사용하여 테이블의 레코드를 정렬 할 수 있습니다. 다음 SELECT 문은 열 age 및 FIRST_NAME을 기준으로 CRICKETERS 테이블의 레코드를 정렬합니다.

postgres=# SELECT * FROM CRICKETERS ORDER BY AGE, FIRST_NAME;
 first_name | last_name  | age | place_of_birth | country
------------+------------+-----+----------------+-------------
Virat       | Kohli      | 30  | Delhi          | India
Rohit       | Sharma     | 32  | Nagpur         | India
Shikhar     | Dhawan     | 33  | Delhi          | India
Jonathan    | Trott      | 38  | CapeTown       | SouthAfrica
Kumara      | Sangakkara | 41  | Matale         | Srilanka
(5 rows)

기본적으로 ORDER BY절은 테이블의 레코드를 오름차순으로 정렬합니다. DESC를 사용하여 결과를 내림차순으로 정렬 할 수 있습니다.

postgres=# SELECT * FROM CRICKETERS ORDER BY AGE DESC;
 first_name | last_name  | age | place_of_birth | country
------------+------------+-----+----------------+-------------
Kumara      | Sangakkara | 41  | Matale         | Srilanka
Jonathan    | Trott      | 38  | CapeTown       | SouthAfrica
Shikhar     | Dhawan     | 33  | Delhi          | India
Rohit       | Sharma     | 32  | Nagpur         | India
Virat       | Kohli      | 30  | Delhi          | India
(5 rows)

Python을 사용한 ORDER BY 절

특정 순서로 테이블의 내용을 검색하려면 커서 개체에서 execute () 메서드를 호출하고 ORDER BY 절과 함께 SELECT 문을 매개 변수로 전달합니다.

예

다음 예에서는 ORDER BY 절을 사용하여 이름과 직원이있는 테이블을 만들고, 채우고, 해당 레코드를 나이의 (오름차순) 순서로 다시 검색합니다.

import psycopg2
#establishing the connection
conn = psycopg2.connect(
   database="mydb", user='postgres', password='password', host='127.0.0.1', port= '5432'
)

#Setting auto commit false
conn.autocommit = True

#Creating a cursor object using the cursor() method
cursor = conn.cursor()

#Doping EMPLOYEE table if already exists.
cursor.execute("DROP TABLE IF EXISTS EMPLOYEE")

#Creating a table
sql = '''CREATE TABLE EMPLOYEE(
   FIRST_NAME CHAR(20) NOT NULL,
   LAST_NAME CHAR(20),
   AGE INT, SEX CHAR(1),
   INCOME INT,
   CONTACT INT)'''
cursor.execute(sql)

#Populating the table
insert_stmt = "INSERT INTO EMPLOYEE 
   (FIRST_NAME, LAST_NAME, AGE, SEX, INCOME, CONTACT) VALUES (%s, %s, %s, %s, %s, %s)"

data = [('Krishna', 'Sharma', 26, 'M', 2000, 101), 
   ('Raj', 'Kandukuri', 20, 'M', 7000, 102),
   ('Ramya', 'Ramapriya', 29, 'F', 5000, 103),
   ('Mac', 'Mohan', 26, 'M', 2000, 104)]
cursor.executemany(insert_stmt, data)
conn.commit()

#Retrieving specific records using the ORDER BY clause
cursor.execute("SELECT * from EMPLOYEE ORDER BY AGE")
print(cursor.fetchall())

#Commit your changes in the database
conn.commit()

#Closing the connection
conn.close()

산출

[('Sharukh', 'Sheik', 25, 'M', 8300.0), ('Sarmista', 'Sharma', 26, 'F', 10000.0)]

UPDATE 문을 사용하여 PostgreSQL에서 테이블의 기존 레코드 내용을 수정할 수 있습니다. 특정 행을 업데이트하려면 WHERE 절을 함께 사용해야합니다.

통사론

다음은 PostgreSQL의 UPDATE 문의 구문입니다.

UPDATE table_name
SET column1 = value1, column2 = value2...., columnN = valueN
WHERE [condition];

예

다음 쿼리를 사용하여 이름이 CRICKETERS 인 테이블을 생성했다고 가정합니다.

postgres=# CREATE TABLE CRICKETERS ( 
   First_Name VARCHAR(255), Last_Name VARCHAR(255), Age int, 
   Place_Of_Birth VARCHAR(255), Country VARCHAR(255)
);
CREATE TABLE
postgres=#

그리고 INSERT 문을 사용하여 5 개의 레코드를 삽입했다면-

postgres=# insert into CRICKETERS values('Shikhar', 'Dhawan', 33, 'Delhi', 'India');
INSERT 0 1
postgres=# insert into CRICKETERS values('Jonathan', 'Trott', 38, 'CapeTown', 'SouthAfrica');
INSERT 0 1
postgres=# insert into CRICKETERS values('Kumara', 'Sangakkara', 41, 'Matale', 'Srilanka');
INSERT 0 1
postgres=# insert into CRICKETERS values('Virat', 'Kohli', 30, 'Delhi', 'India');
INSERT 0 1
postgres=# insert into CRICKETERS values('Rohit', 'Sharma', 32, 'Nagpur', 'India');
INSERT 0 1

다음 문은 이름이 크리켓 선수의 나이를 수정합니다. Shikhar −

postgres=# UPDATE CRICKETERS SET AGE = 45 WHERE FIRST_NAME = 'Shikhar' ;
UPDATE 1
postgres=#

FIRST_NAME이 Shikhar 인 레코드를 검색하면 나이 값이 45로 변경된 것을 볼 수 있습니다.

postgres=# SELECT * FROM CRICKETERS WHERE FIRST_NAME = 'Shikhar';
 first_name | last_name | age | place_of_birth | country
------------+-----------+-----+----------------+---------
Shikhar     | Dhawan    | 45  | Delhi          | India
(1 row)

postgres=#

WHERE 절을 사용하지 않은 경우 모든 레코드의 값이 업데이트됩니다. 다음 UPDATE 문은 CRICKETERS 테이블에있는 모든 레코드의 나이를 1 씩 증가시킵니다.

postgres=# UPDATE CRICKETERS SET AGE = AGE+1;
UPDATE 5

SELECT 명령을 사용하여 테이블의 내용을 검색하면 업데이트 된 값을 다음과 같이 볼 수 있습니다.

postgres=# SELECT * FROM CRICKETERS;
 first_name | last_name  | age | place_of_birth | country
------------+------------+-----+----------------+-------------
Jonathan    | Trott      | 39  | CapeTown       | SouthAfrica
Kumara      | Sangakkara | 42  | Matale         | Srilanka
Virat       | Kohli      | 31  | Delhi          | India
Rohit       | Sharma     | 33  | Nagpur         | India
Shikhar     | Dhawan     | 46  | Delhi          | India
(5 rows)

Python을 사용하여 레코드 업데이트

psycopg2의 커서 클래스는 execute () 메서드라는 이름의 메서드를 제공합니다. 이 메서드는 쿼리를 매개 변수로 받아들이고 실행합니다.

따라서 Python을 사용하여 PostgreSQL의 테이블에 데이터를 삽입하려면-

  • 수입 psycopg2 꾸러미.

  • 다음을 사용하여 연결 개체를 만듭니다. connect() 사용자 이름, 암호, 호스트 (선택적 기본값 : localhost) 및 데이터베이스 (선택적)를 매개 변수로 전달합니다.

  • 속성 값으로 false를 설정하여 자동 커미트 모드를 끄십시오. autocommit.

  • 그만큼 cursor() 의 방법 Connectionpsycopg2 라이브러리의 클래스는 커서 객체를 반환합니다. 이 메서드를 사용하여 커서 개체를 만듭니다.

  • 그런 다음 execute () 메서드에 매개 변수로 전달하여 UPDATE 문을 실행합니다.

예

다음 Python 코드는 Employee 테이블의 내용을 업데이트하고 결과를 검색합니다.

import psycopg2
#establishing the connection
conn = psycopg2.connect (
   database="mydb", user='postgres', password='password', host='127.0.0.1', port= '5432'
)

#Setting auto commit false
conn.autocommit = True

#Creating a cursor object using the cursor() method
cursor = conn.cursor()

#Fetching all the rows before the update
print("Contents of the Employee table: ")
sql = '''SELECT * from EMPLOYEE'''
cursor.execute(sql)
print(cursor.fetchall())

#Updating the records
sql = "UPDATE EMPLOYEE SET AGE = AGE + 1 WHERE SEX = 'M'"
cursor.execute(sql)
print("Table updated...... ")

#Fetching all the rows after the update
print("Contents of the Employee table after the update operation: ")
sql = '''SELECT * from EMPLOYEE'''
cursor.execute(sql)
print(cursor.fetchall())

#Commit your changes in the database
conn.commit()

#Closing the connection
conn.close()

산출

Contents of the Employee table:
[
   ('Ramya', 'Rama priya', 27, 'F', 9000.0), 
   ('Vinay', 'Battacharya', 20, 'M', 6000.0), 
   ('Sharukh', 'Sheik', 25, 'M', 8300.0), 
   ('Sarmista', 'Sharma', 26, 'F', 10000.0), 
   ('Tripthi', 'Mishra', 24, 'F', 6000.0)
]
Table updated......
Contents of the Employee table after the update operation:
[
   ('Ramya', 'Rama priya', 27, 'F', 9000.0), 
   ('Sarmista', 'Sharma', 26, 'F', 10000.0), 
   ('Tripthi', 'Mishra', 24, 'F', 6000.0), 
   ('Vinay', 'Battacharya', 21, 'M', 6000.0), 
   ('Sharukh', 'Sheik', 26, 'M', 8300.0)
]

다음을 사용하여 기존 테이블의 레코드를 삭제할 수 있습니다. DELETE FROMPostgreSQL 데이터베이스의 문. 특정 레코드를 제거하려면 WHERE 절을 함께 사용해야합니다.

통사론

다음은 PostgreSQL의 DELETE 쿼리 구문입니다.

DELETE FROM table_name [WHERE Clause]

예

다음 쿼리를 사용하여 이름이 CRICKETERS 인 테이블을 생성했다고 가정합니다.

postgres=# CREATE TABLE CRICKETERS ( 
   First_Name VARCHAR(255), Last_Name VARCHAR(255), Age int, 
   Place_Of_Birth VARCHAR(255), Country VARCHAR(255)
);
CREATE TABLE
postgres=#

그리고 INSERT 문을 사용하여 5 개의 레코드를 삽입했다면-

postgres=# insert into CRICKETERS values ('Shikhar', 'Dhawan', 33, 'Delhi', 'India');
INSERT 0 1
postgres=# insert into CRICKETERS values ('Jonathan', 'Trott', 38, 'CapeTown', 'SouthAfrica');
INSERT 0 1
postgres=# insert into CRICKETERS values ('Kumara', 'Sangakkara', 41, 'Matale', 'Srilanka');
INSERT 0 1
postgres=# insert into CRICKETERS values ('Virat', 'Kohli', 30, 'Delhi', 'India');
INSERT 0 1
postgres=# insert into CRICKETERS values ('Rohit', 'Sharma', 32, 'Nagpur', 'India');
INSERT 0 1

다음 문장은 성이 '상악 카라'인 크리켓 선수의 기록을 삭제합니다.

postgres=# DELETE FROM CRICKETERS WHERE LAST_NAME = 'Sangakkara';
DELETE 1

SELECT 문을 사용하여 테이블의 내용을 검색하면 하나를 삭제했기 때문에 4 개의 레코드 만 볼 수 있습니다.

postgres=# SELECT * FROM CRICKETERS;
 first_name | last_name | age | place_of_birth | country
------------+-----------+-----+----------------+-------------
Jonathan    |     Trott |  39 | CapeTown       | SouthAfrica
Virat       |     Kohli |  31 | Delhi          | India
Rohit       |    Sharma |  33 | Nagpur         | India
Shikhar     |    Dhawan |  46 | Delhi          | India

(4 rows)

WHERE 절없이 DELETE FROM 문을 실행하면 지정된 테이블의 모든 레코드가 삭제됩니다.

postgres=# DELETE FROM CRICKETERS;
DELETE 4

모든 레코드를 삭제 했으므로 CRICKETERS 테이블의 내용을 검색하려고하면 SELECT 문을 사용하여 아래와 같이 빈 결과 집합을 얻게됩니다.

postgres=# SELECT * FROM CRICKETERS;
 first_name | last_name | age | place_of_birth | country
------------+-----------+-----+----------------+---------
(0 rows)

Python을 사용하여 데이터 삭제

psycopg2의 커서 클래스는 execute () 메서드라는 이름의 메서드를 제공합니다. 이 메서드는 쿼리를 매개 변수로 받아들이고 실행합니다.

따라서 Python을 사용하여 PostgreSQL의 테이블에 데이터를 삽입하려면-

  • 수입 psycopg2 꾸러미.

  • 다음을 사용하여 연결 개체를 만듭니다. connect() 사용자 이름, 암호, 호스트 (선택적 기본값 : localhost) 및 데이터베이스 (선택적)를 매개 변수로 전달합니다.

  • 속성 값으로 false를 설정하여 자동 커미트 모드를 끄십시오. autocommit.

  • 그만큼 cursor() 의 방법 Connectionpsycopg2 라이브러리의 클래스는 커서 객체를 반환합니다. 이 메서드를 사용하여 커서 개체를 만듭니다.

  • 그런 다음 DELETE 문을 매개 변수로 execute () 메서드에 전달하여 실행합니다.

예

다음 Python 코드는 나이 값이 25보다 큰 EMPLOYEE 테이블의 레코드를 삭제합니다.

import psycopg2
#establishing the connection
conn = psycopg2.connect(
   database="mydb", user='postgres', password='password', host='127.0.0.1', port= '5432'
)

#Setting auto commit false
conn.autocommit = True

#Creating a cursor object using the cursor() method
cursor = conn.cursor()

#Retrieving contents of the table
print("Contents of the table: ")
cursor.execute('''SELECT * from EMPLOYEE''')
print(cursor.fetchall())

#Deleting records
cursor.execute('''DELETE FROM EMPLOYEE WHERE AGE > 25''')

#Retrieving data after delete
print("Contents of the table after delete operation ")
cursor.execute("SELECT * from EMPLOYEE")
print(cursor.fetchall())

#Commit your changes in the database
conn.commit()

#Closing the connection
conn.close()

산출

Contents of the table:
[
   ('Ramya', 'Rama priya', 27, 'F', 9000.0), 
   ('Sarmista', 'Sharma', 26, 'F', 10000.0), 
   ('Tripthi', 'Mishra', 24, 'F', 6000.0), 
   ('Vinay', 'Battacharya', 21, 'M', 6000.0), 
   ('Sharukh', 'Sheik', 26, 'M', 8300.0)
]
Contents of the table after delete operation:
[  
   ('Tripthi', 'Mishra', 24, 'F', 6000.0), 
   ('Vinay', 'Battacharya', 21, 'M', 6000.0)
]

DROP TABLE 문을 사용하여 PostgreSQL 데이터베이스에서 테이블을 삭제할 수 있습니다.

통사론

다음은 PostgreSQL의 DROP TABLE 문의 구문입니다.

DROP TABLE table_name;

예

다음 쿼리를 사용하여 CRICKETERS 및 EMPLOYEES라는 이름의 두 테이블을 만들었다 고 가정합니다.

postgres=# CREATE TABLE CRICKETERS (
   First_Name VARCHAR(255), Last_Name VARCHAR(255), Age int, 
   Place_Of_Birth VARCHAR(255), Country VARCHAR(255)
);
CREATE TABLE
postgres=#
postgres=# CREATE TABLE EMPLOYEE(
   FIRST_NAME CHAR(20) NOT NULL, LAST_NAME CHAR(20), 
   AGE INT, SEX CHAR(1), INCOME FLOAT
);
CREATE TABLE
postgres=#

이제“\ dt”명령을 사용하여 테이블 목록을 확인하면 위에서 만든 테이블을 다음과 같이 볼 수 있습니다.

postgres=# \dt;
            List of relations
 Schema | Name       | Type  | Owner
--------+------------+-------+----------
 public | cricketers | table | postgres
 public | employee   | table | postgres
(2 rows)
postgres=#

다음 문은 데이터베이스에서 Employee라는 테이블을 삭제합니다-

postgres=# DROP table employee;
DROP TABLE

Employee 테이블을 삭제 했으므로 테이블 목록을 다시 검색하면 테이블 하나만 관찰 할 수 있습니다.

postgres=# \dt;
            List of relations
Schema  | Name       | Type  | Owner
--------+------------+-------+----------
public  | cricketers | table | postgres
(1 row)


postgres=#

Employee 테이블을 다시 삭제하려고하면 이미 삭제했기 때문에 아래와 같이 "테이블이 존재하지 않습니다"라는 오류 메시지가 표시됩니다.

postgres=# DROP table employee;
ERROR: table "employee" does not exist
postgres=#

이를 해결하기 위해 DELTE 문과 함께 IF EXISTS 절을 사용할 수 있습니다. 테이블이 있으면 제거하고 DLETE 작업을 건너 뜁니다.

postgres=# DROP table IF EXISTS employee;
NOTICE: table "employee" does not exist, skipping
DROP TABLE
postgres=#

Python을 사용하여 전체 테이블 제거

DROP 문을 사용하여 필요할 때마다 테이블을 삭제할 수 있습니다. 단, 테이블 삭제 후 손실 된 데이터는 복구되지 않으므로 기존 테이블 삭제시 매우주의해야합니다.

import psycopg2
#establishing the connection
conn = psycopg2.connect(database="mydb", user='postgres', password='password', host='127.0.0.1', port= '5432')

#Setting auto commit false
conn.autocommit = True

#Creating a cursor object using the cursor() method
cursor = conn.cursor()

#Doping EMPLOYEE table if already exists
cursor.execute("DROP TABLE emp")
print("Table dropped... ")

#Commit your changes in the database
conn.commit()

#Closing the connection
conn.close()

산출

#Table dropped...

PostgreSQL SELECT 문을 실행하는 동안 LIMIT 절을 사용하여 결과의 ​​레코드 수를 제한 할 수 있습니다.

통사론

다음은 PostgreSQL의 LMIT 절 구문입니다.

SELECT column1, column2, columnN
FROM table_name
LIMIT [no of rows]

예

다음 쿼리를 사용하여 이름이 CRICKETERS 인 테이블을 생성했다고 가정합니다.

postgres=# CREATE TABLE CRICKETERS (
   First_Name VARCHAR(255), Last_Name VARCHAR(255), 
   Age int, Place_Of_Birth VARCHAR(255), Country VARCHAR(255)
);
CREATE TABLE
postgres=#

그리고 INSERT 문을 사용하여 5 개의 레코드를 삽입했다면-

postgres=# insert into CRICKETERS values ('Shikhar', 'Dhawan', 33, 'Delhi', 'India');
INSERT 0 1
postgres=# insert into CRICKETERS values ('Jonathan', 'Trott', 38, 'CapeTown', 'SouthAfrica');
INSERT 0 1
postgres=# insert into CRICKETERS values ('Kumara', 'Sangakkara', 41, 'Matale', 'Srilanka');
INSERT 0 1
postgres=# insert into CRICKETERS values ('Virat', 'Kohli', 30, 'Delhi', 'India');
INSERT 0 1
postgres=# insert into CRICKETERS values ('Rohit', 'Sharma', 32, 'Nagpur', 'India');
INSERT 0 1

다음 문은 LIMIT 절을 사용하여 Cricketers 테이블의 처음 3 개 레코드를 검색합니다.

postgres=# SELECT * FROM CRICKETERS LIMIT 3;
 first_name | last_name  | age | place_of_birth | country
------------+------------+-----+----------------+-------------
 Shikhar    | Dhawan     | 33  | Delhi          | India
 Jonathan   | Trott      | 38  | CapeTown       | SouthAfrica
 Kumara     | Sangakkara | 41  | Matale         | Srilanka

   (3 rows)

특정 레코드 (오프셋)에서 시작하는 레코드를 가져 오려면 LIMIT와 함께 OFFSET 절을 사용하면됩니다.

postgres=# SELECT * FROM CRICKETERS LIMIT 3 OFFSET 2;
 first_name | last_name  | age | place_of_birth | country
------------+------------+-----+----------------+----------
 Kumara     | Sangakkara | 41  | Matale         | Srilanka
 Virat      | Kohli      | 30  | Delhi          | India
 Rohit      | Sharma     | 32  | Nagpur         | India

   (3 rows)
postgres=#

Python을 사용한 제한 조항

다음 파이썬 예제는 EMPLOYEE라는 테이블의 내용을 검색하여 결과의 ​​레코드 수를 2로 제한합니다.

import psycopg2
#establishing the connection
conn = psycopg2.connect(
   database="mydb", user='postgres', password='password', host='127.0.0.1', port= '5432'
)

#Setting auto commit false
conn.autocommit = True

#Creating a cursor object using the cursor() method
cursor = conn.cursor()

#Retrieving single row
sql = '''SELECT * from EMPLOYEE LIMIT 2 OFFSET 2'''

#Executing the query
cursor.execute(sql)

#Fetching the data
result = cursor.fetchall();
print(result)

#Commit your changes in the database
conn.commit()

#Closing the connection
conn.close()

산출

[('Sharukh', 'Sheik', 25, 'M', 8300.0), ('Sarmista', 'Sharma', 26, 'F', 10000.0)]

데이터를 두 테이블로 나눈 경우 조인을 사용하여이 두 테이블에서 결합 된 레코드를 가져올 수 있습니다.

예

CRICKETERS라는 이름의 테이블을 만들고 아래와 같이 5 개의 레코드를 삽입했다고 가정합니다.

postgres=# CREATE TABLE CRICKETERS (
   First_Name VARCHAR(255), Last_Name VARCHAR(255), Age int, 
   Place_Of_Birth VARCHAR(255), Country VARCHAR(255)
);
postgres=# insert into CRICKETERS values ('Shikhar', 'Dhawan', 33, 'Delhi', 'India');
postgres=# insert into CRICKETERS values ('Jonathan', 'Trott', 38, 'CapeTown', 'SouthAfrica');
postgres=# insert into CRICKETERS values ('Kumara', 'Sangakkara', 41, 'Matale', 'Srilanka');
postgres=# insert into CRICKETERS values ('Virat', 'Kohli', 30, 'Delhi', 'India');
postgres=# insert into CRICKETERS values ('Rohit', 'Sharma', 32, 'Nagpur', 'India');

그리고 OdiStats라는 이름으로 다른 테이블을 만들고 5 개의 레코드를 삽입했다면

postgres=# CREATE TABLE ODIStats (
   First_Name VARCHAR(255), Matches INT, Runs INT, AVG FLOAT, 
   Centuries INT, HalfCenturies INT
);
postgres=# insert into OdiStats values ('Shikhar', 133, 5518, 44.5, 17, 27);
postgres=# insert into OdiStats values ('Jonathan', 68, 2819, 51.25, 4, 22);
postgres=# insert into OdiStats values ('Kumara', 404, 14234, 41.99, 25, 93);
postgres=# insert into OdiStats values ('Virat', 239, 11520, 60.31, 43, 54);
postgres=# insert into OdiStats values ('Rohit', 218, 8686, 48.53, 24, 42);

다음 문은이 두 테이블의 값을 결합한 데이터를 검색합니다.

postgres=# SELECT
   Cricketers.First_Name, Cricketers.Last_Name, Cricketers.Country,
   OdiStats.matches, OdiStats.runs, OdiStats.centuries, OdiStats.halfcenturies
   from Cricketers INNER JOIN OdiStats ON Cricketers.First_Name = OdiStats.First_Name;
 first_name | last_name  | country     | matches | runs  | centuries | halfcenturies
------------+------------+-------------+---------+-------+-----------+---------------
 Shikhar    | Dhawan     | India       | 133     | 5518  | 17        | 27
 Jonathan   | Trott      | SouthAfrica | 68      | 2819  | 4         | 22
 Kumara     | Sangakkara | Srilanka    | 404     | 14234 | 25        | 93
 Virat      | Kohli      | India       | 239     | 11520 | 43        | 54
 Rohit      | Sharma     | India       | 218     | 8686  | 24        | 42
(5 rows)
   
postgres=#

Python을 사용한 조인

데이터를 두 테이블로 나눈 경우 조인을 사용하여이 두 테이블에서 결합 된 레코드를 가져올 수 있습니다.

예

다음 파이썬 프로그램은 JOIN 절의 사용법을 보여줍니다-

import psycopg2
#establishing the connection
conn = psycopg2.connect(
   database="mydb", user='postgres', password='password', host='127.0.0.1', port= '5432'
)

#Setting auto commit false
conn.autocommit = True

#Creating a cursor object using the cursor() method
cursor = conn.cursor()

#Retrieving single row
sql = '''SELECT * from EMP INNER JOIN CONTACT ON EMP.CONTACT = CONTACT.ID'''

#Executing the query
cursor.execute(sql)

#Fetching 1st row from the table
result = cursor.fetchall();
print(result)

#Commit your changes in the database
conn.commit()

#Closing the connection
conn.close()

산출

[
   ('Ramya', 'Rama priya', 27, 'F', 9000.0, 101, 101, '[email protected]', 'Hyderabad'), 
   ('Vinay', 'Battacharya', 20, 'M', 6000.0, 102, 102, '[email protected]', 'Vishakhapatnam'), 
   ('Sharukh', 'Sheik', 25, 'M', 8300.0, 103, 103, '[email protected] ', 'Pune'), 
   ('Sarmista', 'Sharma', 26, 'F', 10000.0, 104, 104, '[email protected]', 'Mumbai')
]

psycopg 라이브러리의 Cursor 클래스는 Python 코드를 사용하여 데이터베이스에서 PostgreSQL 명령을 실행하는 메서드를 제공합니다.

그것의 방법을 사용하면 SQL 문을 실행하고, 결과 집합에서 데이터를 가져오고, 프로 시저를 호출 할 수 있습니다.

당신은 만들 수 있습니다 Cursor Connection 객체 / 클래스의 cursor () 메서드를 사용하는 객체.

예

import psycopg2
#establishing the connection
conn = psycopg2.connect(
   database="mydb", user='postgres', password='password', host='127.0.0.1', port= '5432'
)

#Setting auto commit false
conn.autocommit = True

#Creating a cursor object using the cursor() method
cursor = conn.cursor()

행동 양식

다음은 Cursor 클래스 / 객체에서 제공하는 다양한 메서드입니다.

Sr. 아니. 방법 및 설명
1

callproc()

이 메서드는 기존 프로 시저 PostgreSQL 데이터베이스를 호출하는 데 사용됩니다.

2

close()

이 메서드는 현재 커서 개체를 닫는 데 사용됩니다.

삼

executemany()

이 메소드는 일련의 매개 변수 목록을 허용합니다. MySQL 쿼리를 준비하고 모든 매개 변수를 사용하여 실행합니다.

4

execute()

이 메소드는 MySQL 쿼리를 매개 변수로 받아들이고 주어진 쿼리를 실행합니다.

5

fetchall()

이 메서드는 쿼리 결과 집합의 모든 행을 검색하여 튜플 목록으로 반환합니다. (몇 개의 행을 검색 한 후 이것을 실행하면 나머지 행을 반환합니다)

6

fetchone()

이 메서드는 쿼리 결과에서 다음 행을 가져 와서 튜플로 반환합니다.

7

fetchmany()

이 메소드는 fetchone ()과 유사하지만 단일 행 대신 쿼리의 결과 세트에서 다음 행 세트를 검색합니다.

속성

다음은 Cursor 클래스의 속성입니다-

Sr. 아니. 속성 및 설명
1

description

결과 집합의 열 설명이 포함 된 목록을 반환하는 읽기 전용 속성입니다.

2

lastrowid

이는 읽기 전용 속성입니다. 테이블에 자동 증가 된 열이있는 경우 마지막 INSERT 또는 UPDATE 작업에서 해당 열에 대해 생성 된 값을 반환합니다.

삼

rowcount

SELECT 및 UPDATE 작업의 경우 반환 / 업데이트 된 행 수를 반환합니다.

4

closed

이 속성은 커서가 닫혀 있는지 여부를 지정합니다. 그럴 경우 true를 반환하고 그렇지 않으면 false를 반환합니다.

5

connection

이 커서가 생성 된 연결 개체에 대한 참조를 반환합니다.

6

name

이 속성은 커서의 이름을 반환합니다.

7

scrollable

이 속성은 특정 커서를 스크롤 할 수 있는지 여부를 지정합니다.