Preface
In fact, in Python can be used to connect the module of PostgreSQL many, here is recommended psycopg2. PSYCOPG2 is very simple to install ( pip install psycopg2
), here are the main highlights of how to use.
To connect to a database:
Import Psycopg2conn = 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 you do not provide a default connection to UNIX sockets)
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 () # No, this method commits the current transaction. If this method is not called, no matter what changes have been made, since the last Call to #commit () is not visible conn.close ()
also supports parameterization when 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 that the content of this article on everyone's study or work can bring certain help, if there is doubt you can message exchange.