How Python connects to the PostgreSQL database

Source: Internet
Author: User
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.

  • 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.