Objective
In fact, there are many modules that can be used to connect PostgreSQL in Python, here it is recommended psycopg2. PSYCOPG2 installation is very simple ( pip install psycopg2
), here is the main focus on how to use.
To connect to a database:
Import PSYCOPG2
conn = Psycopg2.connect (host= "10.100.157.168", user= "Postgres", password= "Postgres", database= " TestDB ")
Parameters available when connecting:
dbname– database name (DSN connection mode)
database– database name
user– User Name
password– Password
host– server address (if 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 () # query without, this method commits the current transaction. If this method is not invoked, no matter what modifications have been made, the last call to #commit () is not visible
conn.close ()
Supports parameterization in addition to executing SQL
Syntax:cursor.execute(sql [, optional parameters])
Case:cursor.execute("insert into people values (%s, %s)", (who, age))
Summarize
The above is the entire content of this article, I hope the content of this article for everyone's study or work can bring certain help, if you have questions you can message exchange.