close
The Wayback Machine - https://web.archive.org/web/20090204171156/http://python.about.com:80/od/pythonanddatabases/ss/dbpostgresql_7.htm

Python

  1. Home
  2. Computing & Technology
  3. Python

Inserting Data Into a PostgreSQL Database

By Al Lukaszewski, 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

More from About.com

New Year, New You

Take action today to accomplish your biggest goals with these motivating ideas.

Best Moves in a Bad Economy

Stay on top in this tough economy with our smart, easy-to-follow financial tips.

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.