PythonPostgreSQL-クイックガイド

PostgreSQLは、強力なオープンソースのオブジェクトリレーショナルデータベースシステムです。15年以上の活発な開発フェーズと、信頼性、データの整合性、および正確性で高い評価を得ている実証済みのアーキテクチャを備えています。

Pythonを使用してPostgreSQLと通信するには、Pythonプログラミング用に提供されているアダプターであるpsycopgをインストールする必要があります。現在のバージョンは次のとおりです。 psycog2

psycopg2は、非常に小さくて速く、岩のように安定することを目的として作成されました。PIP(Pythonのパッケージマネージャー)で利用できます

PIPを使用したPsycog2のインストール

まず、Pythonと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シェルプロンプトを開き、サーバー、データベース、ユーザー名、パスワードなどの詳細を渡します。指定したすべての詳細が適切である場合、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シェルプロンプトでこのステートメントを実行できます。

構文

以下は、CREATEDATABASEステートメントの構文です。

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ステートメントCREATEDATABASEのラッパーであるコマンド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でデータベースを作成するには、このメソッドを使用してCREATEDATABASEクエリを実行します。

次の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のCREATETABLEステートメントの構文です。

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のカーソルのexecute()メソッドを使用してCREATETABLEステートメントを実行する必要があります。

次の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、...はテーブルに挿入する必要のある値です。

以下に示すように、CREATETABLEステートメントを使用して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()メソッドに渡して、INSERTステートメントを実行します。

次の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クエリは、列FIRST_NAME、LAST_NAME、およびCOUNTRYの値をCRICKETERSテーブルから取得します。

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を使用したデータの取得

任意のデータベースでのREAD操作は、データベースからいくつかの有用な情報をフェッチすることを意味します。psycopg2が提供するfetch()メソッドを使用して、PostgreSQLからデータをフェッチできます。

Cursorクラスは、fetchall()、fetchmany()、およびfetchone()の3つのメソッドを提供します。ここで、

  • 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句

Pythonプログラムを使用してテーブルから特定のレコードをフェッチするには、WHERE句を指定してSELECTステートメントを実行し、それをパラメーターとしてexecute() 方法。

次のPythonの例は、Pythonを使用した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のORDERBY句の構文です。

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を使用したORDERBY句

テーブルの内容を特定の順序で取得するには、カーソルオブジェクトでexecute()メソッドを呼び出し、SELECTステートメントとORDERBY句をパラメータとして渡します。

次の例では、名前とEmployeeを使用してテーブルを作成し、そのテーブルにデータを入力し、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ライブラリのクラスはカーソルオブジェクトを返します。このメソッドを使用してカーソルオブジェクトを作成します。

  • 次に、UPDATEステートメントをパラメーターとしてexecute()メソッドに渡して実行します。

次の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

次のステートメントは、姓が「Sangakkara」であるクリケット選手のレコードを削除します。

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

SELECTステートメントを使用してテーブルの内容を取得すると、1つを削除したため、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句を指定せずにDELETEFROMステートメントを実行すると、指定したテーブルのすべてのレコードが削除されます。

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のDROPTABLEステートメントの構文です。

DROP TABLE table_name;

次のクエリを使用して、CRICKETERSとEMPLOYEESという名前の2つのテーブルを作成したと仮定します。

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テーブルを削除したため、テーブルのリストを再度取得すると、その中のテーブルは1つしか監視できません。

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ステートメントとともにIFEXISTS句を使用できます。これにより、テーブルが存在する場合は削除され、存在しない場合は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を使用した制限句

次の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)]

データを2つのテーブルに分割すると、結合を使用してこれら2つのテーブルから結合されたレコードをフェッチできます。

以下に示すように、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);

次のステートメントは、これら2つのテーブルの値を組み合わせたデータを取得します-

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を使用して結合

データを2つのテーブルに分割すると、結合を使用してこれら2つのテーブルから結合されたレコードをフェッチできます。

次の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クラス/オブジェクトによって提供されるさまざまなメソッドです。

シニア番号 方法と説明
1

callproc()

このメソッドは、既存のプロシージャPostgreSQLデータベースを呼び出すために使用されます。

2

close()

このメソッドは、現在のカーソルオブジェクトを閉じるために使用されます。

3

executemany()

このメソッドは、一連のパラメーターリストのリストを受け入れます。MySQLクエリを準備し、すべてのパラメータを使用して実行します。

4

execute()

このメソッドは、MySQLクエリをパラメータとして受け入れ、指定されたクエリを実行します。

5

fetchall()

このメソッドは、クエリの結果セット内のすべての行を取得し、それらをタプルのリストとして返します。(いくつかの行を取得した後にこれを実行すると、残りの行が返されます)

6

fetchone()

このメソッドは、クエリの結果の次の行をフェッチし、それをタプルとして返します。

7

fetchmany()

このメソッドはfetchone()に似ていますが、単一の行ではなく、クエリの結果セット内の次の行のセットを取得します。

プロパティ

Cursorクラスのプロパティは次のとおりです-

シニア番号 プロパティと説明
1

description

これは、結果セットの列の説明を含むリストを返す読み取り専用プロパティです。

2

lastrowid

これは読み取り専用プロパティです。テーブルに自動インクリメントされた列がある場合、これは最後のINSERTまたはUPDATE操作でその列に対して生成された値を返します。

3

rowcount

これは、SELECTおよびUPDATE操作の場合に返される/更新された行の数を返します。

4

closed

このプロパティは、カーソルが閉じているかどうかを指定します。閉じている場合はtrueを返し、閉じていない場合はfalseを返します。

5

connection

これは、このカーソルが作成された接続オブジェクトへの参照を返します。

6

name

このプロパティは、カーソルの名前を返します。

7

scrollable

このプロパティは、特定のカーソルがスクロール可能かどうかを指定します。