Python

  1. Home
  2. Computing & Technology
  3. Python

Inserting Data Into a PostgreSQL Database

From Al Lukaszewski, for About.com

7 of 7

Put it All Together And Call It

Finally, we have a function for inserting data into a table of our choice, using columns and values defined as needed.

def insert(table, columns, values):
'''Function to insert the form data 'values' into table 'table'
according to the columns in 'column' '''

     connection = psycopg.connect('dbname=Birds', 'user=robert')
     mark = connection.cursor()
     statement = 'INSERT INTO ' + table + ' (' + columns + ') VALUES (' + values + ')'
     mark.execute(statement)
     connection.commit()
     return

To call this function, we simply need to define the table, columns, and values and pass them as follows:

type = "Owls"
fields = "id, kind, date"
values = "17965, Barn owl, 2006-07-16"

insert(type, fields, values)

Explore Python

About.com Special Features

Build Your Own Website

Step-by-step advice on how to do everything from choosing a Web host to promoting your content. More >

Connect Your Home Computers

Easy ways to connect two computers for networking purposes. More >

Python

  1. Home
  2. Computing & Technology
  3. Python
  4. Database Programming
  5. Python and PostgreSQL - Inserting Data Into a PostgreSQL Database - Put the Python Parts Together And Call the Function

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

All rights reserved.