1. Computing

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) 

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

©2013 About.com. All rights reserved.