Python-data-access-python-postgresql-where-clause

提供:Dev Guides
移動先:案内検索

Python PostgreSQL-Where句

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