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")
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()
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.