This article describes how to connect to a PostgreSQL database using Python.
CONNECTING TO POSTGRESQL USING PYTHON
Before you can access PostgreSQL databases using Python, you must install one (or more) of the following packages in a virtual environment:
Both of these packages support Python's portable SQL database API. This means that if you switch from one module to another, you can reuse almost all of your existing code (the code sample below demonstrates how to do this). Setting up the Python virtual environment and installing a PostgreSQL package. To set up the Python virtual environment and install a PostgreSQL package, follow these steps:
1. Log in to your account using SSH.
2. To create a virtual environment, type the following commands:
3. To activate the virtual environment, type the following command:
4. Type the command for the package you want to install:
To install the psycopg2 package, type the following command:
To install the PyGreSQL package, type the following command:
Code sample using Python's portable SQL database API
After you install a PostgreSQL package in the virtual environment, you are ready to work with actual databases. The following sample Python code demonstrates how to do this, as well as just how easy it is to switch between the different SQL package implementations using the portable SQL database API.
In your own code, replace USERNAME with the PostgreSQL database username, PASSWORD with the database user's password, and DBNAME with the database name. Let's have below testing table for demonstration:
* Python 文章收集 - Virtual Environments
* How To Install and Use PostgreSQL on CentOS 7
* “FATAL: IDENT AUTHENTICATION FAILED”, OR HOW COOL IDEAS GET BAD USAGE SCHEMAS