Python realizes method analysis of connecting to postgresql database

  • 2020-06-19 10:55:08
  • OfStack

This article illustrates how Python implements a connection to an postgresql database. To share for your reference, specific as follows:

python can connect postgresql through the third module. The more famous ones are psycopg2 and python3-ES9en

(1) psycopg2

ubuntu install


sudo apt-get install python3-psycopg2

Create 1 test. py file


import psycopg2
#  Database connection parameters 
conn = 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 table
print(rows)
 conn.commit()
 cur.close()
 conn.close()

When run, it appears as follows


[(2, 'jack', 'girl'), (1, 'max', 'boy '), (3, 'kate', 'girl')]

(2) python3 - postgresql

ubuntu install


sudo apt-get install python3-postgresql

Create the file and run it


import postgresql
 #('pq:// The user name : password @localhost:5432/ The database name ')
db = postgresql.open('pq://jm:123@localhost:5432/test1')
ps=db.prepare("select * from a1")
print(ps())
ps.close()
db.close()

More about Python related content interested readers to view this site project: "common database operations Python skills summary", "Python mathematical operation skills summary", "Python data structure and algorithm tutorial", "Python function using techniques", "Python string skills summary", "Python introduction and advanced tutorial" and "Python file and directory skills summary"

I hope this article has been helpful in Python programming.


Related articles: