Python-data-access-python-postgresql-update-table
提供:Dev Guides
Python PostgreSQL-更新テーブル
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 パッケージをインポートします。
- ユーザー名、パスワード、ホスト(オプションのデフォルト:localhost)、およびデータベース(オプション)をパラメーターとして渡すことにより、 _ connect()_ メソッドを使用して接続オブジェクトを作成します。
- 属性 autocommit の値としてfalseを設定して、自動コミットモードをオフにします。
- psycopg2ライブラリの Connection クラスの* cursor()*メソッドは、カーソルオブジェクトを返します。 このメソッドを使用してカーソルオブジェクトを作成します。 *次に、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)]