1. Home
  2. Computing & Technology
  3. Python

Inserting Data Into a PostgreSQL Database

From Al Lukaszewski, for 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.

Explore Python
About.com Special Features

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

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

  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

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

All rights reserved.