Python connection PostgreSQL Database method _python

Source: Internet
Author: User
Tags commit postgresql in python

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.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.