Format SQL in Python with Psycopg's Mogrify
Last Updated :
24 Mar, 2022
Psycopg, the Python PostgreSQL driver, includes a very useful mechanism for formatting SQL in python, which is mogrify.
After parameters binding, returns a query string. The string returned is the same as what SQLwas sent to the database if you used the execute() function or anything similar. One may use the same inputs for mogrify() as you would for execute(), and the outcome will be as expected.
Installation:
We need to install the psycopg2 module in python to call various functions in use to fulfill the requirements.
Syntax:
pip install psycopg2
cursor.mogrify() method:
cursor.mogrify() method returns a query string once the parameters have been bound. If you used the execute() method or anything similar, the string returned is the same as what would be sent to the database. The resulting string is always a bytes string, which is quicker than using the executemany() function.
Syntax:
cur.mogrify("INSERT INTO table_name (column) VALUES (%s, %s....)", (value1, value2,...)(......))
Example:
psycopg2 package is imported, a connection to the database is established using psycopg2.connection() method. Autocommit is set to true and a cursor is created using conn.cursor() method. A table is created in the database and cursor.mogrify() method is used to create a formatted SQL to insert values into the table. Cursor.mogrify() gives a bytes string, but we want it to be in string format, thus we only need to use the decode('UTF-8') technique to decode the output of mogrify back to a string. Later data is fetched using the fetchall() method and changes are committed.
Python3
# importing packages
import psycopg2
# forming connection
conn = psycopg2.connect(
database="Emp_database",
user='postgres',
password='pass',
host='127.0.0.1',
port='5432'
)
conn.autocommit = True
# creating a cursor
cursor = conn.cursor()
cursor.execute(
'create table emp_table(emp_code int,\
emp_name varchar(30), emp_salary decimal)')
# list of rows to be inserted
values = [(34545, 'samuel', 48000.0),
(34546, 'rachel', 23232),
(34547, 'Sean', 92000.0)]
# cursor.mogrify() to insert multiple values
args = ','.join(cursor.mogrify("(%s,%s,%s)", i).decode('utf-8')
for i in values)
# executing the sql statement
cursor.execute("INSERT INTO emp_table VALUES " + (args))
# select statement to display output
sql1 = '''select * from emp_table;'''
# executing sql statement
cursor.execute(sql1)
# fetching rows
for i in cursor.fetchall():
print(i)
# committing changes
conn.commit()
# closing connection
conn.close()
Output:
(34545, 'samuel', Decimal('48000.0'))
(34546, 'rachel', Decimal('23232'))
(34547, 'Sean', Decimal('92000.0'))

Similar Reads
Executing SQL query with Psycopg2 in Python In this article, we are going to see how to execute SQL queries in PostgreSQL using Psycopg2 in Python. Psycopg2 is a PostgreSQL database driver, it is used to perform operations on PostgreSQL using python, it is designed for multi-threaded applications. SQL queries are executed with psycopg2 with t
2 min read
Python | Getting started with psycopg2-PostGreSQL PostgreSQL is a powerful, open source object-relational database system. PostgreSQL runs on all major operating systems. PostgreSQL follows ACID property of DataBase system and has the support of triggers, updatable views and materialized views, foreign keys. To connect PostgreSQL we use psycopg2 .
1 min read
How to Use SSL Mode in psycopg2 using Python SSL Mode in psycopg2 enhances security for database connections using SSL mode in psycopg2, a popular PostgreSQL adapter for Python. SSL mode settings should be provided in the connection string or parameters. It is used through the setting of a parameter known as sslmode, which identifies the level
8 min read
Perform Insert Operations with psycopg2 in Python psycopg2 is a widely used Python library designed to facilitate communication with PostgreSQL databases, offering a robust and efficient way to perform various database operations. It is a powerful and flexible connector, which allows Python applications to execute SQL commands and handle data seaml
9 min read
Comparing psycopg2 vs psycopg in Python PostgreSQL is a powerful, open-source relational database management system known for its robustness, extensibility, and standards compliance. It supports a wide range of data types and complex queries, making it suitable for various applications, from small web applications to large enterprise syst
7 min read