1. Home
  2. Computing & Technology
  3. Python

Inserting Data Into a PostgreSQL Database

From , former About.com Guide

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

Holiday Central

What to eat, where to go, fun things to do and how to save money on the perfect gifts. More >

Family Tech Center

Stay connected and entertained with reviews on tips on the latest HDTVs, cellphones and more. More >

  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.