Python can connect to PostgreSQL via a third-party module. More famous psycopg2 and Python3-postgresql.
(a) PSYCOPG2
Install under Ubuntu
sudo Install PYTHON3-PSYCOPG2
Create a test.py file
ImportPSYCOPG2#Database Connection Parametersconn = Psycopg2.connect (database="test1", user="JM", password="123", host="127.0.0.1", port="5432") cur=conn.cursor () Cur.execute ("SELECT * from A1;") Rows= Cur.fetchall ()#All rows in tablePrint(rows)
Conn.commit ()
Cur.close ()
Conn.close ()
The following is displayed after running
[(2'jack'girl'), (1'max ") , (3'Kate' ' Girl ')]
(ii) Python3-postgresql
Install under Ubuntu
sudo Install Python3-postgresql
Create a file and run
Import PostgreSQL # ('pq://username: password @localhost:5432/database name '= Postgresql.open ('pq://jm:[email protected]:5432/test1') PS=db.prepare ( " SELECT * FROM A1 " )print(PS ()) Ps.close () db.close ()
Python connects to the PostgreSQL database