Preface
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:
Note.
3. To activate the virtual environment, type the following command:
Note.
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:
- List of relations
- Schema | Name | Type | Owner
- --------+-------------------+----------+-------
- public | users | table | john
- public | users_name_id_seq | sequence | john
- (2 rows)
- name_id | name | age | location | birthday
- --------+-------+-----+-----------+------------
- 1 | John | 38 | tw | 1980-07-31
- 2 | Mary | 25 | east | 1989-07-31
- 3 | Peter | 32 | southeast | 1982-02-03
- 3 rows)
- postgresqlEx.py
- #!/usr/bin/env python2
- hostname = '127.0.0.1'
- username = 'john'
- password = ''
- database = 'john'
- # Simple routine to run a query on a database and print the results:
- def doQuery( conn ) :
- cur = conn.cursor()
- cur.execute( "SELECT name, age, location FROM users" )
- for name, age, location in cur.fetchall() :
- print("{} from {} with age={}".format(name, location, age))
- print "Using psycopg2..."
- import psycopg2
- conn = psycopg2.connect(host = hostname, user= username, password=password, dbname=database)
- doQuery( conn )
- conn.close()
- #print "Using PyGreSQL..."
- #import pgdb
- #conn = pgdb.connect( host=hostname, user=username, password=password, database=database )
- #doQuery( conn )
- #conn.close()
Supplement
* Python 文章收集 - Virtual Environments
* How To Install and Use PostgreSQL on CentOS 7
* “FATAL: IDENT AUTHENTICATION FAILED”, OR HOW COOL IDEAS GET BAD USAGE SCHEMAS
沒有留言:
張貼留言