Home > Backend Development > Python Tutorial > How to connect to PostgreSQL database in Python

How to connect to PostgreSQL database in Python

WBOY
Release: 2016-12-05 13:27:22
Original
2296 people have browsed it

Foreword

In fact, there are many modules that can be used to connect to PostgreSQL in Python, and psycopg2 is recommended here. psycopg2 is very simple to install (pip install psycopg2). Here we mainly focus on how to use it.

Connect to database:

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

Available parameters when connecting:

dbname – database name (dsn connection mode)

database – database name

      user – username

password – password

Host – server address (if the default connection Unix Socket is not provided)

port – connection port (default 5432)

Execute 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() # 查询时无需,此方法提交当前事务。如果不调用这个方法,无论做了什么修改,自从上次调用#commit()是不可见的
conn.close()
Copy after login

In addition, parameterization is supported when executing SQL

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

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

Summary

The above is the entire content of this article. I hope the content of this article can bring some help to everyone's study or work. If you have any questions, you can leave a message to communicate.

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template