Is it safe to use string concatenation for dynamic SQL queries in Python with psycopg2

+1 vote

I’m developing a Python application that interacts with a PostgreSQL database using psycopg2. In certain places, I’m building dynamic SQL queries by concatenating user input with query strings. 

For instance, I have something like this:

query = "SELECT * FROM users WHERE username = '" + user_input + "';"

I’ve heard that this approach might expose the application to SQL injection attacks, but I’m not sure how vulnerable it is in practice, especially since I’m using psycopg2. Is it generally unsafe to use string concatenation like this, and if so, what’s the best alternative to safely handle dynamic queries?

Oct 17 in Cyber Security & Ethical Hacking by Anupam
• 6,190 points
127 views

1 answer to this question.

+1 vote

The use of string concatenation while building dynamic SQL queries can expose your application to SQL Injection Attacks, even if you're using psycopg2.

Although, psycopg2 provides some safety, but concatenating user input into SQL strings in risky.

Consider the following example:

query = "SELECT * FROM users WHERE username = '" + user_input + "';"

Here, the attacker could manipulate user_input to execute arbitrary SQL commands.

So, instead of concatenating strings, use parameterized queries, which are safer:

query = "SELECT * FROM users WHERE username = %s;"
cursor.execute(query, (user_input,))

This will ensure that user input is treated as data, not as part of the SQL command.

answered Oct 17 by CaLLmeDaDDY
• 9,150 points

Thanks for explaining this so clearly! I didn’t realize how risky string concatenation could be, even with psycopg2. Parameterized queries seem like a much safer option.

Related Questions In Cyber Security & Ethical Hacking

0 votes
1 answer

How to use Python to read block of data in txt file and convert it to structured data?

Okay, I understand. To extract structured data ...READ MORE

answered Apr 19, 2023 in Cyber Security & Ethical Hacking by Edureka
• 12,690 points
1,632 views
0 votes
0 answers
+1 vote
1 answer

How do you decrypt a ROT13 encryption on the terminal itself?

Yes, it's possible to decrypt a ROT13 ...READ MORE

answered Oct 17 in Cyber Security & Ethical Hacking by CaLLmeDaDDY
• 9,150 points
123 views
+1 vote
1 answer
+1 vote
1 answer
+1 vote
1 answer
+1 vote
1 answer

What is the best way to use APIs for DNS footprinting in Node.js?

There are several APIs that can help ...READ MORE

answered Oct 17 in Cyber Security & Ethical Hacking by CaLLmeDaDDY
• 9,150 points
164 views
+1 vote
1 answer
webinar REGISTER FOR FREE WEBINAR X
REGISTER NOW
webinar_success Thank you for registering Join Edureka Meetup community for 100+ Free Webinars each month JOIN MEETUP GROUP