How to connect Python to PostgreSQL database

Source: Internet
Author: User
Everyone should know that python can operate a variety of databases, such as SQLite, MySql, and PostgreSQL. I will not repeat all database operation methods here, this document briefly introduces PostgreSQL used in the current project. it mainly describes how to connect Python to the PostgreSQL database. If you need it, you can refer to it for reference. let's take a look at it. Preface

In fact, there are many modules in Python that can be used to connect to PostgreSQL. Here we recommend psycopg2. Psycopg2 is easy to install (pip install psycopg2). Here we will focus on how to use it.

Connect to the database:

import psycopg2conn = psycopg2.connect(host="10.100.157.168",user="postgres",password="postgres",database="testdb")

Available parameters during connection:

Dbname-database name (dsn connection mode)

Database-database name

User-user name

Password-password

Host-server address (if no default Unix Socket is provided)

Port-connection port (5432 by default)

Execute SQL

Import psycopg2 conn = psycopg2.connect (host = "10.100.157.168", port = 5432, user = "s", password = "postgres", database = "testdb") cur = conn. cursor () SQL = "" cur.exe cute (SQL) conn. commit () # No need to query. this method commits the current transaction. If you do not call this method, no matter what changes have been made, since the last call # commit () is invisible conn. close ()

In addition, parameterization is supported during SQL execution.

Syntax: cursor.execute(sql [, optional parameters])

Case: cursor.execute("insert into people values (%s, %s)", (who, age))

Summary

The above is all about this article. I hope this article will help you in your study or work. if you have any questions, please leave a message.

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.