Python

  1. Home
  2. Computing & Technology
  3. Python

Inserting Data Into a PostgreSQL Database

From Al Lukaszewski, for About.com

2 of 7

Python to PostgreSQL: Open Sesame

To open a connection to a database, psycopg needs two arguments: the name of the database ('dbname') and the name of the user ('user'). The syntax for opening a connection follows this format:

<variable name for connection> = psycopg.connect('dbname=<dbname>', 'user=<user>')

For our database, we shall use the database name 'Birds' and the username 'robert'. For the connection object within the program, let's use the variable 'connection'. So, our connection command will read as follows:

connection = psycopg.connect('dbname=Birds', 'user=robert')

Naturally, this command will only work if both variables are accurate: there must be a real database named 'Birds' to which a user named 'robert' has access. If either of these conditions are not filled, Python will throw an error.

Explore Python

About.com Special Features

Python

  1. Home
  2. Computing & Technology
  3. Python
  4. Database Programming
  5. Python and PostgreSQL - Inserting Data Into a PostgreSQL Database - Python to PostgreSQL: Open Sesame

©2009 About.com, a part of The New York Times Company.

All rights reserved.