The method by which Python connects to the PostgreSQL database

  • 2020-05-17 05:50:03
  • OfStack

preface

In fact, there are many modules that can be used to connect PostgreSQL in Python, and psycopg2 is recommended here. psycopg2 is very simple to install ( pip install psycopg2 ), here the main focus of how to use.

Connect to database:


import psycopg2
conn = psycopg2.connect(host="10.100.157.168",user="postgres",password="postgres",database="testdb")

Available parameters for connection:

Database name of dbname (dsn connection mode)

The database name of database

The user name of user

password � password

host server address (if default connection is not provided)

port connection port (default 5432)

Perform SQL


import psycopg2
 
conn = psycopg2.connect(host="10.100.157.168",port=5432,user="postgres",password="postgres",database="testdb")
cur = conn.cursor()
sql = ""
cur.execute(sql)
conn.commit() #  This method commits the current transaction without the need to query. If this method is not called, whatever changes have been made since the last call #commit() It's invisible 
conn.close()

In addition, parameterization is supported when performing SQL

Grammar: cursor.execute(sql [, optional parameters])

Case study: cursor.execute("insert into people values (%s, %s)", (who, age))

conclusion

The above is the whole content of this article, I hope the content of this article to your study or work can bring 1 definite help, if you have questions you can leave a message to communicate.


Related articles: