1. Home
  2. Computing & Technology
  3. Python

Inserting Data Into a PostgreSQL Database

By Al Lukaszewski, About.com

4 of 7

Separating PostgreSQL Form and Python Function

While some SQL insertion formats allow for understood or unstated column structure, we will be using the following template for our insert statements:

INSERT INTO <table> (columns) VALUES (values) ;

While we could pass a statement in this format to the psycopg method 'execute' and so insert data into the database, this quickly becomes convoluted and confusing. A better way is to compartmentalize the statement separately from the 'execute' command as follows:

statement = 'INSERT INTO ' + table + ' (' + columns + ') VALUES (' + values + ')'
mark.execute(statement)

In this way, form is kept separate from function. Such separation often helps in debugging.

4 of 7

Explore Python

More from About.com

  1. Home
  2. Computing & Technology
  3. Python
  4. Database Programming
  5. Python and PostgreSQL - Inserting Data Into a PostgreSQL Database - Separating PostgreSQL Form and Python Function

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

All rights reserved.