You are on page 1of 28

PostgreSQL Python tutorial This is a Python programming tutorial for the PostgreSQL database. It covers the basics of PostgreSQL programming with the Python language. You might also want to check the Python tutorial or PostgreSQL PHP tutorial on ZetCode. Several libraries exist for connecting to the PostgreSQL database from the Python language. In this tutorial we will use the psycopg2 module. It is a PostgreSQL database adapter for the Python programming language. According to the module documentation it is currently the most popular Python module for the PostgreSQL database. It is mostly implemented in C as a libpq wrapper.

About PostgreSQL database
PostgreSQL is a powerful, open source object-relational database system. It is a multiuser, multi-threaded database management system. It runs on multiple platforms including Linux, FreeBSD, Solaris, Microsoft Windows and Mac OS X. PostgreSQL is developed by the PostgreSQL Global Development Group.

To work with this tutorial, we must have Python language, PostgreSQL database and psycopg2 language binding installed on our system.
$ sudo apt-get install postgresql

On an Ubuntu based system we can install the PostgreSQL database using the above command.
$ sudo update-rc.d -f postgresql remove Removing any system startup links for /etc/init.d/postgresql ... /etc/rc0.d/K21postgresql /etc/rc1.d/K21postgresql /etc/rc2.d/S19postgresql /etc/rc3.d/S19postgresql /etc/rc4.d/S19postgresql /etc/rc5.d/S19postgresql /etc/rc6.d/K21postgresql

If we install the PostgreSQL database from packages, it is automatically added to the start up scripts of the operating system. If we are only learning to work with the database, it is unnecessary to start the database each time we boot the system. The above command removes any system startup links for the PostgreSQL database.
$ /etc/init.d/postgresql status Running clusters: 9.1/main $ service postgresql status Running clusters: 9.1/main

We check if the PostgreSQL server is running. If not, we need to start the server.
$ sudo service postgresql start * Starting PostgreSQL 9.1 database server [ OK ]

On Ubuntu Linux we can start the server with the service postgresql start command.
$ sudo service postgresql stop [sudo] password for janbodnar: * Stopping PostgreSQL 9.1 database server

[ OK ]

We use the service postgresql stop command to stop the PostgreSQL server.
$ sudo apt-get install python-psycopg2

Here we install the psycopg2 module on a Ubuntu system.
$ sudo -u postgres createuser janbodnar Shall the new role be a superuser? (y/n) n Shall the new role be allowed to create databases? (y/n) y Shall the new role be allowed to create more new roles? (y/n) n

We create a new role in the PostgreSQL system. We allow it to have ability to create new databases. A role is a user in a database world. Roles are separate from operating system users. We have created a new user without the -W option, e.g. we have not specified a password. This enables us to connect to a database with this user without password authentication. Note that this works only on localhost.
$ sudo -u postgres createdb testdb -O janbodnar

The createdb command creates a new PostgreSQL database with the owner janbodnar.

In the first code example, we will get the version of the PostgreSQL database.
#!/usr/bin/python # -*- coding: utf-8 -*import psycopg2 import sys con = None try: con = psycopg2.connect(database='testdb', user='janbodnar') cur = con.cursor() cur.execute('SELECT version()') ver = cur.fetchone() print ver except psycopg2.DatabaseError, e: print 'Error %s' % e sys.exit(1) finally: if con: con.close()

In the above Python script we connect to the previously created testdb database. We execute an SQL statement which returns the version of the PostgreSQL database.

we get the cursor script. con = psycopg2. user='janbodnar') The connect() method creates a new database session and returns a connection object.DatabaseError. Since we retrieve only one record.2 on i686-pc-linux-gnu. e: print 'Error %s' % e sys. 32-bit (1 row) Running the version. cur = con. Otherwise. con = None We initialize the con variable to None. This would lead to an error in the finally clause.6. we print an error message and exit the script with an error code 1.1. finally: if con: con.exit(1) In case of an exception.connect(database='testdb'. The user was created without a password. we can omit the password option. Inserting data We will create a Cars table and insert several rows to it. In case we could not create a connection to the database (for example the disk is full).6. On localhost.execute('SELECT version()') From the version ----------------------------------------------------------------------------------------------------------PostgreSQL 9. we call the fetchone() method.cursor() cur. it must be specified. The cursor is used to traverse the records from the result set.fetchone() We fetch the data. er = cur.real (Ubuntu/Linaro 4. we would not have a connection variable defined. $ ./version. except psycopg2.import psycopg2 The psycopg2 is a Python module which is used to work with the PostgreSQL database.6.1. .1-9ubuntu3) 4. We call the execute() method of the cursor and execute the SQL statement. compiled by gcc-4. print ver We print the data that we have retrieved to the console.close()) In the final step. we release the resources.

execute("INSERT INTO cars VALUES(6.52642)") cur.execute("CREATE TABLE cars(id INT PRIMARY KEY. cur.'Skoda'.'Bentley'. if con: con.execute("INSERT INTO Cars VALUES(1. con.execute("INSERT INTO cars VALUES(7. The table has three columns.41400)") cur. we roll back any possible changes to our database table.'Hummer'.'Mercedes'.'Audi'. e: if con: con.21600)") con.9000)") cur. $ psql testdb psql (9. price INT)") This SQL statement creates a new cars table.commit() except psycopg2.close() The above script creates a Cars table and inserts 8 rows into the table.execute("INSERT INTO cars VALUES(5.'Citroen'.#!/usr/bin/python # -*.1. cur.execute("INSERT INTO cars VALUES(2.execute("INSERT INTO cars VALUES(4.exit(1) finally: if con: con. name VARCHAR(20).execute("CREATE TABLE cars(id INT PRIMARY KEY.execute("INSERT INTO cars VALUES(3. name VARCHAR(20).execute("INSERT INTO cars VALUES(8.DatabaseError.52642)") cur.57127)") cur.commit() The changes are committed to the database.2) .350000)") cur.29000)") cur.'Volvo'.21000)") cur.connect(database='testdb'. price INT)") cur.execute("INSERT INTO cars VALUES(1.execute("INSERT INTO Cars VALUES(2.cursor() cur.'Volkswagen'.'Mercedes'.coding: utf-8 -*import psycopg2 import sys con = None try: con = psycopg2.rollback() print 'Error %s' % e sys.'Audi'. user='janbodnar') cur = con.57127)") These two lines insert two cars into the table.rollback() In case of an error.

(3. 41400). %s)" cur.connect(database='testdb'. 21000). 29000). price INT)") query = "INSERT INTO cars (id. (5. 52642). id | name | price ----+------------+-------1 | Audi | 52642 2 | Mercedes | 57127 3 | Skoda | 9000 4 | Volvo | 29000 5 | Bentley | 350000 6 | Citroen | 21000 7 | Hummer | 41400 8 | Volkswagen | 21600 (8 rows) We verify the written data with the psql tool. cars) con. 'Skoda'. (6. (8. e: if con: con. 'Volvo'. #!/usr/bin/python # -*.Type "help" for help. name TEXT. testdb=> SELECT * FROM cars. (4. price) VALUES (%s.commit() except psycopg2. user='janbodnar') cur = con.execute("DROP TABLE IF EXISTS cars") cur. 21600) ) con = None try: con = psycopg2.cursor() cur. %s. 'Bentley'. 'Hummer'. 'Volkswagen'.executemany(query. We are going to create the same table. 9000).coding: utf-8 -*import psycopg2 import sys cars = ( (1. 57127). (2.DatabaseError. This time using the convenience executemany() method. 350000). name. 'Citroen'.execute("CREATE TABLE cars(id INT PRIMARY KEY. (7.exit(1) finally: . 'Audi'.rollback() print 'Error %s' % e sys. 'Mercedes'.

%s. in the form of tuple of tuples.executemany(query. cur. that we have inserted some data into the database. name.close() In this example.close() This script drops a Cars table if it exists and (re)creates it. The second SQL statement creates the Cars table. %s)" This is the query that we will use. price) VALUES (%s. price INT)") The first SQL statement drops the Cars table. cur. we retrieve all data from the cars table.DatabaseError. e: print 'Error %s' % e sys. cars) We insert 8 rows into the table using the convenience executemany() method. #!/usr/bin/python # -*.execute("CREATE TABLE cars(id INT PRIMARY KEY. cur.coding: utf-8 -*import psycopg2 import sys con = None try: con = psycopg2. The second parameter is the data. Retrieving data Now.cursor() cur.if con: con. The first parameter of this method is a parameterized SQL statement. query = "INSERT INTO cars (id. name TEXT.fetchall() for row in rows: print row except psycopg2.execute("SELECT * FROM cars") rows = cur. user='janbodnar') cur = con. we want to get it back.exit(1) finally: if con: con.execute("SELECT * FROM Cars") . if it exists.connect(database='testdb'.execute("DROP TABLE IF EXISTS cars") cur.

row[2] except psycopg2.DatabaseError. 'Skoda'. We can fetch rows one by one. 29000) (5. #!/usr/bin/python # -*. 'Audi'. Each of the inner tuples represent a row in the table./fetch1. 'Mercedes'. for row in rows: print row We print the data to the console. 'Hummer'. it is a tuple of tuples.cursor() cur.connect(database='testdb'. 350000) (6. e: print 'Error %s' % e sys. 9000) (4.fetchall() The fetchall() method gets all records. 57127) ( (1. 'Volkswagen'. 'Bentley'. row[1]. $ . It returns a result set. 21000) (7. 21600) This is the output of the example.This SQL statement selects all data from the Cars table. 52642) (2. 'Citroen'. 'Volvo'.coding: utf-8 -*import psycopg2 import sys con = None try: con = psycopg2. rows = cur.fetchone() if row == None: break print row[0]. Returning all data at a time may not be feasible.execute("SELECT * FROM cars") while True: row = cur.exit(1) finally: if con: con. 41400) (8. Technically.close() . row by row. user='janbodnar') cur = con.

connect(database='testdb'.extras import sys con = None try: con = psycopg2.fetchone() if row == None: break The fetchone() method returns the next row from the table./retrieveonebyone. When we read the last row. This way we can refer to the data by their column names. Here we select records from the tuple.In this script we connect to the database and fetch the rows of the cars table one by one.execute("SELECT * FROM Cars") rows = cursor. In this case we break the loop. row[1].py Audi 52642 Mercedes 57127 Skoda 9000 Volvo 29000 Bentley 350000 Citroen 21000 Hummer 41400 Volkswagen 21600 This is the output of the example. print row[0]. If there is no more data left. The dictionary cursor The default cursor returns the data in a tuple of tuples.cursor(cursor_factory=psycopg2. row["price"]) .fetchall() for row in rows: print "%s %s %s" % (row["id"]. row[2] The data is returned in the form of a tuple. the data is sent in a form of Python dictionaries. while True: We access the data from the while loop. it returns None.extras. row["name"]. the second is the car name and the third is the price of the car. When we use a dictionary cursor. the loop is terminated. row = cur.coding: utf-8 -*import psycopg2 import psycopg2. #!/usr/bin/python # -*.DictCursor) cursor. user='janbodnar') cursor = con. The first is the Id. $ 1 2 3 4 5 6 7 8 .

connect(database='testdb'.execute("UPDATE Cars SET price=%s WHERE id=%s". #!/usr/bin/python # -*. e: print 'Error %s' % e sys.rowcount except psycopg2. cursor = con. import psycopg2. we use placeholders instead of directly writing the values into the statements.except psycopg2.DictCursor) We create a DictCursor.cursor(cursor_factory=psycopg2. (uPrice. Parameterized queries Now we will concern ourselves with parameterized queries. Parameterized queries increase security and performance.extras The dictionary cursor is located in the extras module. row["price"]) The data is accessed by the column names. The Python psycopg2 module supports two types of placeholders. When we use parameterized queries. Ansi C printf format and Python extended format.DatabaseError. e: if con: .DatabaseError.commit() print "Number of rows updated: %d" % cur.coding: utf-8 -*import psycopg2 import sys con = None uId = 1 uPrice = 62300 try: con = psycopg2. for row in rows: print "%s %s %s" % (row["id"].extras.cursor() cur.close() In this example. we print the contents of the cars table using the dictionary cursor. user='janbodnar') cur = con. uId)) con. row["name"].exit(1) finally: if con: con.

The second example uses parameterized statements with Python extended format./prepared. $ .rowcount The rowcount property returns the number of updated rows.close() We update a price of one car.execute("SELECT * FROM cars WHERE id=%(id)s". #!/usr/bin/python # -*. id | name | price ----+------+------1 | Audi | 62300 (1 row) The price of the car was updated.connect(database='testdb'.execute("UPDATE Cars SET price=%s WHERE id=%s".exit(1) .rollback() print 'Error %s' % e sys. (uPrice. uId)) The characters (%s) are placeholders for values.cursor() cur.DatabaseError. print "Number of rows updated: %d" % cur.coding: utf-8 -*import psycopg2 import sys con = None uid = 3 try: con = Number of rows updated: 1 testdb=> SELECT * FROM cars WHERE id=1.fetchone() except psycopg2. In our case one row was updated. cur. In this code example.exit(1) finally: if con: con. {'id': uid } ) print cur. The values are added to the placeholders.con. user='janbodnar') cur = con. we use the question mark placeholders. e: print 'Error %s' % e sys. We check the change with the psql tool.

args[0].cursor() data = readImage() binary = psycopg2. For the images. {'id': uid } ) The named placeholders start with a colon character. data BYTEA).e. testdb=> CREATE TABLE images(id INT PRIMARY KEY.exit(1) finally: if fin: fin. ( return img except IOError. user="janbodnar") cur = con. For this example. $ . We do not dwell into technical issues of whether to save images in databases or not. Inserting images In this section.close() try: con = psycopg2. cur. %s)".connect(database="testdb".) ) .execute("SELECT * FROM cars WHERE id=%(id)s".finally: if con: con. 'Skoda'.args[1]) sys. "rb") img = fin.execute("INSERT INTO images(id. we are going to insert an image to the PostgreSQL database. data) VALUES (1. It allows to store binary strings. we use the BYTEA data type.coding: utf-8 -*import psycopg2 import sys def readImage(): try: fin = open("woman. #!/usr/bin/python # -*.close() We select a name and a price of a car using pyformat parameterized statement. e: print "Error %d: %s" % (e. we create a new table called images.jpg".Binary(data) (3. 9000) Output of the example. Here we only show how to do it./parameterized2. Note that some people argue against putting images into databases.

Reading images In this section.rollback() print 'Error %s' % e sys.jpg. e: print "Error %d: %s" % (e. We will read an image from the database table. e. (binary.jpg'. we read an image from the current working directory and write it into the images table of the PostgreSQL testdb database. data) VALUES (1. user="janbodnar") . cur.coding: utf-8 -*import psycopg2 import sys def writeImage(data): try: fout = open('woman2.close() In this script. We have a jpg image called woman. %s)". e: if con: con.args[0].con. "rb") img = fin. #!/usr/bin/python # -*.Binary(data) The data is encoded using the psycopg2 Binary object.args[1]) sys.connect(database="testdb". we are going to perform the reverse return img We read binary data from the filesystem.exit(1) finally: if con: con.exit(1) finally: if fout: fout.DatabaseError.execute("INSERT INTO images(id. binary = psycopg2.commit() except psycopg2.close() try: con = psycopg2. try: fin = open("woman.) ) This SQL statement is used to insert the image into the database.'wb') fout.write(data) except IOError.jpg".

cursor() cur. Number of rows and columns returned in a result set belong to metadata as well.rollback() print 'Error %s' % e sys.commit() except psycopg2. We obtain the binary data from the first row.execute("SELECT Data FROM images LIMIT 1") data = cur. Number of rows affected by an SQL statement is a metadata. Metadata Metadata is information about the data in the database. Metadata in a PostgreSQL database contains information about the tables and columns. try: fout = open('woman2.fetchone()[0] These two lines select and fetch data from the Images table.close() We read image data from the images table and write it to another file.exit(1) finally: if con: con.DatabaseError. Metadata in PostgreSQL can be obtained using from the description property of the cursor object or from the information_schema table.coding: utf-8 -*import psycopg2 import sys con = None try: con = psycopg2.fetchone()[0] writeImage(data) con.execute("SELECT Data FROM Images LIMIT 1") data = cur.jpg.'wb') fout. Next we will print all rows from the cars table with their column names. cur.jpg'.connect("dbname='testdb' user='janbodnar'") .cur = con. The data from the database is written to the file. e: if con: con. which we call woman2. #!/usr/bin/python # -*.write(data) We open a binary file in a writing mode. in which we store data.

we include the names of the columns too.cursor() cur. col_names[2]) for row in rows: print "%2s %-10s %s" % row except psycopg2. for row in rows: print "%2s %-10s %s" % row We print the rows using the for loop./colnames. The records are aligned with the column names. e: print 'Error %s' % e sys.fetchall() print "%s %-10s %s" % (col_names[0].exit(1) finally: if con: con. col_names[1].py id name price 2 Mercedes 57127 3 Skoda 9000 4 Volvo 29000 5 Bentley 350000 6 Citroen 21000 7 Hummer 41400 8 Volkswagen 21600 1 Audi 62300 Output. The data is aligned with the column names.coding: utf-8 -*import psycopg2 import sys con = None .close() We print the contents of the cars table to the console.DatabaseError. Now. #!/usr/bin/python # -*. col_names = [cn[0] for cn in cur. col_names[2]) This line prints three column names of the cars table.description] We get the column names from the description property of the cursor object. $ .description] rows = cur.execute('SELECT * FROM cars') col_names = [cn[0] for cn in cur. print "%s %-10s %s" % (col_names[0]. col_names[1]. In the following example we will list all tables in the testdb database.cur = con.

try: con = psycopg2. sep="|") except psycopg2.exit(1) finally: if con: con.execute("""SELECT table_name FROM information_schema.coding: utf-8 -*import psycopg2 import sys con = None fout = None try: con = psycopg2.connect(database='testdb'. Export and import of data We can export and import data using copy_to() and copy_from() methods.cursor() cur.cursor() fout = open('cars.tables WHERE table_schema = 'public'""") rows = cur.connect(database='testdb'.close() The code example prints all available tables in the current database to the terminal. #!/usr/bin/python # -*.fetchall() for row in rows: print row[0] except psycopg2. 'cars'.execute("""SELECT table_name FROM information_schema.DatabaseError.DatabaseError.'w') cur. user='janbodnar') cur = con.sql'. cur. $ . user='janbodnar') cur = cars images friends These were the tables on our system. e: print 'Error %s' % e sys.copy_to(fout. e: print 'Error %s' % e .tables WHERE table_schema = 'public'""") The table names are stored inside the system information_schema table./list_tables.

connect(database='testdb'. 'r') cur. fout = open('cars.copy_to(fout.cursor() f = open('cars'. DELETE 8 We delete the data from the cars table. user='janbodnar') cur = con.'w') We open a file where we will write the data from the cars table.close() In the above example.sql 2|Mercedes|57127 3|Skoda|9000 4|Volvo|29000 5|Bentley|350000 6|Citroen|21000 7|Hummer|41400 8|Volkswagen|21600 1|Audi|62300 The contents of the cars. The columns are separated with a | character.sql file.sql'. testdb=> DELETE FROM cars. #!/usr/bin/python # -*. sep="|") . we copy the data from the cars table into the cars. We will import the dumped table back into the database table. Now we are going to perform a reverse operation. 'cars'.copy_from(f.close() if fout: fout.exit(1) except IOError.sql file. sep="|") The copy_to method copies data from the cars table to the opened file.exit(1) finally: if con: con.sys. e: print 'Error %s' % e sys. cur.coding: utf-8 -*import psycopg2 import sys con = None f = None try: con = psycopg2. $ cat cars. 'cars'.

) The following commands are executed in the context of this new transaction. e: if con: con.exit(1) except IOError. e: if con: con. (We do not need to enclose our SQL commands by BEGIN and END statements to create a transaction. we read the contents of the cars file and copy it back to the cars table.commit() except psycopg2. id | name | price ----+------------+-------1 | Audi | 52642 2 | Mercedes | 57127 3 | Skoda | 9000 4 | Volvo | 29000 5 | Bentley | 350000 6 | Citroen | 21000 7 | Hummer | 41400 8 | Volkswagen | 21600 (8 rows) The output shows. .exit(1) finally: if con: con.copy_from(f. The changes are committed. the transaction is aborted and no further commands are executed until the rollback() method.DatabaseError.con. Transactions A transaction is an atomic unit of database operations against the data in one or more databases. f = open('cars'.commit() We open the cars file for reading and copy the contents to the cars table. that we have successfully recreated the saved cars table. 'cars'. In psycopg2 module transactions are handled by the connection class. sep="|") con. 'r') cur. testdb=> SELECT * FROM cars. The effects of all the SQL statements in a transaction can be either all committed to the database or all rolled back. The first command of a connection cursor starts a transaction.close() In this script.rollback() print 'Error %s' % e sys.close() if f: f. In case of an error. This is handled automatically by psycopg2.rollback() print 'Error %s' % e sys.

The psycopg2 module also supports an autocommit mode. where all changes to the tables are immediately effective.execute("CREATE TABLE friends(id serial PRIMARY KEY. the data will be not committed.execute("INSERT INTO friends(name) VALUES ('Jim')") cur.execute("INSERT INTO friends(name) VALUES ('Tom')") cur. as we will see.commit() except psycopg2.cursor() cur. finally: if con: con. If we uncomment the line.execute("INSERT INTO friends(name) VALUES ('Rebecca')") cur.commit() The commit() method is commented. calling either the commit() or rollback() method.connect(database='testdb'.The documentation to the psycopg2 module says that the connection is responsible to terminate its transaction.close() We create a friends table and try to fill it with data. To run in autocommit mode. e: if con: con. #con. However.execute("DROP TABLE IF EXISTS friends") cur.exit(1) finally: if con: con. we set the autocommit property of the connection object to True. Closing the connection using the close() method or destroying the connection object (using del or letting it fall out of scope) will result in an implicit rollback() call.coding: utf-8 -*import psycopg2 import sys con = None try: con = psycopg2. user='janbodnar') print con. Committed changes are immediately made persistent into the database. name VARCHAR(10))") cur. the data will be written to the table.rollback() print 'Error %s' % e sys.autocommit cur = con.DatabaseError.execute("INSERT INTO friends(name) VALUES ('Robert')") #con.close() . #!/usr/bin/python # -*.

If we have not committed the changes and no error occures (which would roll back the changes) the transaction is still opened.exit(1) finally: if con: con. We don't call neither commit() nor rollback() methods.DatabaseError.execute("INSERT INTO friends(name) VALUES ('Rebecca')") cur.autocommit = True cur = con. .close() In this example.execute("CREATE TABLE friends(id serial PRIMARY KEY.execute("INSERT INTO friends(name) VALUES ('Jim')") cur. name VARCHAR(10))") cur.execute("INSERT INTO friends(name) VALUES ('Robert')") cur.execute("INSERT INTO friends(name) VALUES ('Jane')") cur. an SQL statement is executed immediately.The finally block is always executed.cursor() cur.execute("DROP TABLE IF EXISTS friends") cur. we connect to the database in the autocommit mode.coding: utf-8 -*import psycopg2 import sys con = None try: con = psycopg2. testdb=> \dt List of relations Schema | Name | Type | Owner --------+---------+-------+----------public | cars | table | janbodnar public | friends | table | janbodnar public | images | table | janbodnar (3 rows) Only after we have uncommented the line.execute("INSERT INTO friends(name) VALUES ('Tom')") cur. con. user='janbodnar') con. In the autocommit mode. The connection is closed with the close() method and the transaction is terminated with an implicit call to the rollback() method.execute("INSERT INTO friends(name) VALUES ('Patrick')") except psycopg2.connect(database='testdb'. the friends table is created. #!/usr/bin/python # -*.autocommit = True We set the connection to the autocommit mode. e: print 'Error %s' % e sys.

$ . .py testdb=> SELECT * FROM friends./autocommit. id | name ----+--------1 | Jane 2 | Tom 3 | Rebecca 4 | Jim 5 | Robert 6 | Patrick (6 rows) The data was successfully committed to the friends table.

luego en ejecutamos nuestro script: python La salida deberia ser todos los registros que tenga la tabla "tabla". yo lo hago de la siguiente forma porque me parece la forma mas facil y rapida. cualquier sugerencia es bienvenida: 1.Instalar el modulo de interface entre Python y PostgreSQL.creamos un archivo de nombre conexiondb.passwd=clave) consulta='select * from tabla' print respuesta Hay dos funciones que tenemos que prestar atencion en esta script: Función Parametro Retorno dbname => Nombre de la base de datos a la cual nos vamos a conectar (String)..user=usuario.connect(dbname=base.. passwd => Password del usuarios de la base de datos (String).Conectar Python con PostgreSQL http://cuslanz.query(consulta) que sera el que contendra nuestro script y escribimos dentro: #!/usr/bin/env python import pg usuario='usuario_de_la_base_de_datos' clave='password_de_la_base_de_datos' base='nombre_de_la_base_de_datos' conexion=pg. query(command) close() pgqueryobject => objeto command => Consulta SQL (String) con los resultados de la consulta Ninguno Ninguno pgobject => objeto que maneja la conexión connect([dbname]. #como root aptitude install python-pygresql 2. pero si no hemos configurado la lista de acceso muy probablemente la terminal nos este mostrando un error como este: .ve/22-11-2011/conectar-python-con-postgresql Hay muchas maneras de hacer esto. user => Nombre del usuario de la base de datos a la cual nos conectaremos (String). [passwd]) 3. [user].

ntuples()>0: for fila in respuesta.4/main/pg_hba. print " " Metodos a tomar en cuenta para manipular el resultado de nuestra consulta: Función Parametro Retorno list => resultado de la consulta como una lista de tuplas list => resultado de la consulta como un diccionario o array asociativo de tuplas list => lista con los nombres de los campos String => nombre del campo integer => numero del campo integer => numero de tuplas en el pgqueryobject getresult() Ninguno dictresult() Ninguno listfields() Ninguno i => numero del fieldname(i) campo (int) fieldnum(na name => nombre me) del campo ntuples() Ninguno .getresult(): for col in fila: print col.conf 8.-Si queremos iterar sobre los resultados de la consulta seria algo como: if es la versión de PostgreSQL que tengas instalado y modificamos la autentificación de nuestro usuario de ident a md5 local all all md5 Ahora si deberia funcionar :-) 3.InternalError: FATAL: la autentificaci?n Ident fall? para el usuario <<usurio_de_la_base_de_datos>> lo que debemos hacer es digirnos al siguiente directorio: #como root nano /etc/postgresql/8.


Comment.ActiveSheet.AddComment() xlApp.ClearComments() xlApp. etc. De esa forma poder realizar nuestras aplicaciones. May 1 2007.client import Dispatch Ahora. podemos hacerlo así xlApp. Hay varias formas. "credits" or "license" for more information. esta segunda forma es inmediata.ActiveSheet. no necesitamos nada especial.Value = "Manuel nuñes butron" Podemos.5.) based onPython 2.Workbooks. 17:47:05) [MSC v.Cells(1.ActiveSheet.Visible = 1 Creamos un workbook y ponemos algo en alguna celda xlApp.ActiveSheet.ActiveWorkbook.Text(Text = 'solo para ti) Finalmente. podemos salvar. si queremos. ubicar celdas Imprimir: Datos en la hoja de calculo excel Fin . añadir comentarios a la celda xlApp.Cells(1.El proyecto consiste en vincular o conectar el lenguaje de Programación. pero si no queremos que nos salga el diálogo de "salvar" de Excel.Application") Si la hacemos visible. siguiendo una serie de cadenas de código las cuales generan un Excel desde python.Add()xlApp. FUNDAMENTO TEÓRICO window. se abrirá Excel y veremos lo que estamos haciendo xlApp. biblioteca. 1). Internet.1 (ActiveState Software Inc. 1).google_render_ad(). Si estamos en Windows y tenemos ActivePython instalado. necesitaremos el módulo win32com Abrimos el intérprete de comandos de python c:\> pythonActivePython 2.1310 32 bit (Intel)] onwin32Type "help". en conclusion la clase Dispatch from win32com.1. Python con la hoja electrónica de cálculo Microsoft Excel.Cells(1.1 (r251:54863.Cells(1. 1). Si estamos en Windows pero no tenemos ActivePerl.SaveAs("c:/prueba1.5.xls") DIAGRAMA DE FLUJO INICIO INGRESAR Nº de factura Nombre de cliente Dirección de cliente RUC del cliente Productos Nº productos a factura Precio Unidad de mediada Exportar datos a Excel. "copyright". Para generar un Excel desde Python podemos hacer uso de librerías como pyExcelerator o bien podemos hacerlo directamente usando los objetos COM que nos ofrece Windows.1). pedimos a Windows que nos de un Excel xlApp = Dispatch("Excel.>>> Primero importamos el módulo de win32com. Y para lo cual tuvimos que investigar en diferentes medios de información como son.

Value xlApp.Add() #Escribir etiquetas y datos xlApp.ActiveSheet.Cells(3.Cells(1.ActiveWorkbook.CODIFICACIÓN FACTURA from win32com.1).nro_productos+1): cantidad=float(raw_input("Cantidad:")) detalle=raw_input("Producto:") unidad=raw_input("Unidad Medida:") precio=float(raw_input("Precio:")) #Abrir la aplicacion xlApp = Dispatch("Excel.Value = empresa = etiqueta_cliente = etiqueta_direccion = dir_cliente ." ruc_empresa="1045689777" nro_factura=raw_input("Digite el no.Font.Visible = 1 xlApp.ActiveSheet.A.C.1).ActiveWorkbook.Workbooks.ActiveSheet.1).U.ActiveSheet.Size = 14 xlApp.ActiveSheet. de factura a emitir:") #Datos del cliente razon_social=raw_input("Razon Social del cliente:") ruc_cliente=raw_input("RUC del cliente:") dir_cliente=raw_input("Direccion del cliente:") nro_productos=int(raw_input("Indique el numero de productos a facturar:")) #Solicitar datos de los productos a facturar for i in range(1.V.Application") xlApp.2).ActiveWorkbook.G." etiqueta_valorventa="VALOR DE VENTA" etiqueta_total="TOTAL" etiqueta_precio2="PRECIO2678" #Datos de la empresa empresa="GLOBAL NET S.1).client import Dispatch #Etiquetas del programa etiqueta_cliente="Cliente:" etiqueta_direccion="Direccion:" etiqueta_ruc="R.Value xlApp.C" etiqueta_factura="FACTURA" etiqueta_profac="Producto facturar" etiqueta_cantidad="CANTIDAD" etiqueta_producto="PRODUCTO" etiqueta_unidadmedida="UNIDAD" etiqueta_precio="PRECIO" etiqueta_subtotal="SUBTOTAL" etiqueta_igv="I.Cells(4.Cells(1.Value xlApp.Cells(4.ActiveWorkbook.

Value = "Carlos " xlApp.ActiveSheet.Value = etiqueta_unidadmedida xlApp.ActiveWorkbook.4).ActiveWorkbook.ActiveWorkbook.value = "104" xlApp.Value = etiqueta_ruc xlApp.4).Value = "REGISTRO DE NOTAS" xlApp.ActiveSheet.5).2).ActiveWorkbook.ActiveWorkbook.ActiveWorkbook.Cells(7.1).ActiveSheet.6).ActiveSheet.4).Cells(6.3).value = "103" xlApp.2).ActiveWorkbook.Value = etiqueta_cantidad xlApp.value = "Antonio" xlApp.1).Cells(7.ActiveWorkbook.ActiveWorkbook.Add() xlApp.ActiveWorkbook.Value = etiqueta_producto xlApp.ActiveSheet.Cells(9.2).Cells(9.2).Cells(6.ActiveSheet.Visible = 1 xlApp.ActiveSheet.ActiveSheet.3).Cells(9.ActiveWorkbook.Value = "FIGUEROA MENDOZA" xlApp.Cells(3.Cells(6.5).5).1).ActiveSheet.Value = ruc_empresa xlApp.Value = etiqueta_profac xlApp.Cells(8.Cells(5.Value = "101" xlApp.ActiveSheet.ActiveSheet.ActiveSheet.Cells(3.ActiveWorkbook.2).Value = etiqueta_subtotal xlApp.ActiveSheet.ActiveWorkbook.ActiveSheet.19%" xlApp.Cells(15.6).Cells(4.3).ActiveWorkbook.ActiveWorkbook.ActiveSheet.Formula = "=A9*D9" xlApp.6).2).ActiveSheet.ActiveSheet.ActiveSheet.ActiveWorkbook.Value = "NOMBRES" xlApp.ActiveSheet.Cells(14.Value = etiqueta_total xlApp.Cells(7.Value = nro_factura xlApp.Value = (detalle) xlApp.Cells(7.ActiveWorkbook.Cells(8.ActiveSheet.2).Value = (cantidad) xlApp.ActiveWorkbook.Cells(1.6).ActiveSheet.Value = etiqueta_valorventa xlApp.4).2).3).ActiveWorkbook.Cells(1.Cells(14.ActiveWorkbook.Formula = "=F13*0.Value = ruc_cliente xlApp.Value = nro_productos xlApp.Cells(5.value = "Alberto" xlApp.1).ActiveWorkbook.ActiveWorkbook.Cells(5.Cells(13.ActiveWorkbook.Value = "Nota 1" xlApp.ActiveSheet.Value = (unidad) xlApp.ActiveSheet.ActiveSheet.Workbooks.ActiveWorkbook.6).ActiveSheet.ActiveSheet.ActiveWorkbook.3).ActiveWorkbook.Cells(15.ActiveSheet.Value = "ZORIANO TORRES " xlApp.ActiveWorkbook.ActiveSheet.Cells(5.Cells(13.4).4).ActiveSheet.5).value = "102" xlApp.2).ActiveWorkbook.Value = "DIAZ OJEDA" xlApp.Cells(4.ActiveWorkbook.Value = etiqueta_precio xlApp.3).ActiveSheet.ActiveWorkbook.Cells(4.Cells(8.ActiveSheet.Cells(8.ActiveSheet.ActiveSheet.ActiveSheet.ActiveSheet.ActiveWorkbook.2).Value = "Codigo" xlApp.client import Dispatch xlApp = Dispatch("Excel.Cells(7.value = "13" .1).3).value = "Miguel" xlApp.ActiveWorkbook.1).5).Value = "APELLIDOS" xlApp.ActiveWorkbook.Application") xlApp.ActiveSheet.6).ActiveWorkbook.3).Cells(4.ActiveWorkbook.ActiveWorkbook.Value = "14" xlApp.ActiveSheet.Cells(9.ActiveWorkbook.1).Value = etiqueta_igv xlApp.Cells(2.6).1).ActiveSheet.Cells(5.Value = etiqueta_factura xlApp.ActiveSheet.Cells(1.Cells(9.ActiveSheet.ActiveWorkbook.ActiveWorkbook.Cells(2.Cells(3.Formula = "=F13-F14" producto=[] CODIFICACION NOTAS from win32com.Value = etiqueta_ruc xlApp.Cells(3.Cells(8.ActiveSheet.ActiveSheet.xlApp.Value = (precio) xlApp.ActiveWorkbook.Value = "PEREZ LUNA" xlApp.value = "15" xlApp.1).Cells(6.Formula = "=F9+F10+F11" xlApp.ActiveSheet.ActiveSheet.ActiveWorkbook.ActiveWorkbook.Value = razon_social xlApp.Cells(5.Cells(3.ActiveWorkbook.ActiveWorkbook.ActiveWorkbook.ActiveSheet.

Font.Cells(5.Value = "13" xlApp.3).ActiveWorkbook.ActiveWorkbook.6).ActiveWorkbook.ActiveSheet.3).4).ActiveWorkbook.Value = "15" xlApp.Cells(5.Value = "16" xlApp.AddComment() xlApp.Cells(4.Value = "NOTA 2" xlApp.ActiveSheet.ActiveSheet.ActiveSheet.value = "Promedio" xlApp.Value = "16" xlApp.ActiveSheet.7).8).Size=12 xlApp.Value = "14" xlApp.Cells xlApp.Font.Cells(3.ActiveSheet.Cells(4.Cells(3.ActiveWorkbook.ActiveSheet.Value = "15" xlApp.Cells(3.formula = "=SUM(d4:g4)/4" xlApp.Size=12 xlApp.ActiveSheet.3).6).Font. El uso de dicho programa ha demostrado que también es un lenguaje apto para creación de aplicaciones de tamaño considerable.Cells(7.7).Font.4).ActiveSheet.size=12 xlApp.ActiveWorkbook.5).Cells(6.Cells(1.2).Size=11 xlApp.Text(Text = 'conmigo quien quiera contra mi quien pueda jeje') xlApp.Size=12 xlApp.6).ActiveWorkbook.Cells(4.Value = "15" xlApp.xls") CONCLUSIONES Y RECOMENDACIONES Conclusiones Python resulta un lenguaje muy eficaz para desarrollo rápido de aplicaciones.Value = "16" xlApp.ActiveSheet.ActiveWorkbook.6).ActiveSheet.ActiveWorkbook.ActiveWorkbook.ActiveWorkbook.ActiveSheet.Value = "14" xlApp.5).ActiveSheet.7).Cells(3.ActiveWorkbook.ActiveSheet.Size=17 xlApp.ActiveSheet.Cells(3.ActiveWorkbook.ActiveWorkbook.ActiveWorkbook.5).Cells(3.1).Size=13 xlApp.Cells(3.ActiveWorkbook.SaveAs("c:/prueba1.Comment.6).7).5).Cells(4.ActiveSheet.Size=11 xlApp.ActiveSheet.ActiveWorkbook.7).Cells(3.ActiveSheet.ActiveWorkbook.Font.ActiveSheet.Value = "15" xlApp.Cells(5.ActiveWorkbook.5).3).5).ActiveSheet.ActiveSheet.ActiveSheet.ActiveSheet.ActiveWorkbook.ActiveSheet.Cells(3.Cells(6.ActiveSheet.ActiveSheet.Cells(3.Value = "16" xlApp.Cells xlApp.ActiveWorkbook.value = "15" xlApp.Cells(7.ClearComments() xlApp.ActiveWorkbook.ActiveSheet.ActiveWorkbook.xlApp.ActiveSheet.ActiveWorkbook.Font.Cells(1.Cells(1.Cells(7.Cells(3.ActiveWorkbook.7).ActiveWorkbook.Cells(7.6).8).Value = "NOTA 3" xlApp.Cells(3.Font.ActiveSheet.Font.ActiveWorkbook.Cells(6.ActiveSheet.9).Value = "NOTA 4" xlApp. Su curva de aprendizaje es muy corta por lo que un programador puede dominarlo en poco tiempo Recomendaciones Una de la recomendaciones que en nuestra opinión personal podemos dar seria pues .Value = "12" xlApp.ActiveSheet.

que debemos estudiar y todo lo que leemos y estudiamos nosotros debemos ponerlo en practica para que así no nos olvidemos de los avances realizados. .