

Sql.SQL(',').join(map(sql.Literal, values)) It was introduced in the version 2.7 from psycopg2 import sqlĬolumns = ('country_name_ru', 'airport_name_ru', 'city_code') 'SELECT * FROM engine_airport WHERE city_code = %(city_code)s',Īlso psycopg2 provides the module called sql which can be used to securely form an SQL query. If you need to use the character % you have to write it as %%.Do not use single quotes for string values.Placeholder should be %s for all data types.You should keep in mind the following rules while working with placeholders:

With conn.cursor(cursor_factory=DictCursor) as cursor:ĭid you know that you can form a query using psycopg2? You can do it using format-like placeholders: cursor.execute('SELECT * FROM airport WHERE city_code = %s', ('ALA', )) If you want to get a value by column name you can use NamedTupleCursor or DictCursor: from psycopg2.extras import DictCursor With closing(nnect(.)) as conn:Ĭursor.execute('SELECT * FROM airport LIMIT 5')īy default when you iterate over a cursor (or using the methods mentioned above) you will get a tuple, each column corresponds to its index. Let's do it in a pythonic way using the context manager: from contextlib import closing If you want to follow best practices you need to close a cursor and a connection.
POSTGRESQL PYTHON INSTALL
If you install the psycopg2 you have to have additional source files and compiler (gcc):īut you can install the precompiled binary, in this case you need to execute: pip install psycopg2-binary It is written in C programming language using libpq.

In order "to speak" with a PostgreSQL database pythonistas usually use psycopg2 library. asyncpg is an efficient, clean implementation of PostgreSQL server binary protocol for use with Pythons asyncio framework. Python community likes PostgreSQL as well as PHP community likes MySQL. If you are building a web application you need a database. PostgreSQL is one of the most popular open source database.
