Click here to Skip to main content
15,890,506 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
Consider the code:

mycursor.execute("insert into patients values('"+str(patient)+"','"+name+"','"+age+"','"+gender+"','"+date+"')")
--where patient, name, age, gender, date are variables
I have 3 questions:

What are there two + on both sides of the variable here?
Why are there two quotes (single and double) on both sides of the variable here?
Is there any alternative for this code(without using +)?

What I have tried:

I tried removing the quotes but got into an error
Posted
Updated 25-Jun-21 4:07am

It's a form of string concatenation: Python String Concatenation[^]
And ... it's a very bad idea.

Never concatenate strings to build a SQL command. It leaves you wide open to accidental or deliberate SQL Injection attack which can destroy your entire database. Always use Parameterized queries instead.

When you concatenate strings, you cause problems because SQL receives commands like:
SQL
SELECT * FROM MyTable WHERE StreetAddress = 'Baker's Wood'
The quote the user added terminates the string as far as SQL is concerned and you get problems. But it could be worse. If I come along and type this instead: "x';DROP TABLE MyTable;--" Then SQL receives a very different command:
SQL
SELECT * FROM MyTable WHERE StreetAddress = 'x';DROP TABLE MyTable;--'
Which SQL sees as three separate commands:
SQL
SELECT * FROM MyTable WHERE StreetAddress = 'x';
A perfectly valid SELECT
SQL
DROP TABLE MyTable;
A perfectly valid "delete the table" command
SQL
--'
And everything else is a comment.
So it does: selects any matching rows, deletes the table from the DB, and ignores anything else.

So ALWAYS use parameterized queries! Or be prepared to restore your DB from backup frequently. You do take backups regularly, don't you?
 
Share this answer
 
Python
mycursor.execute("insert into patients values('"+str(patient)+"','"+name+"','"+age+"','"+gender+"','"+date+"')")
                                              123 4           5   6


1. The single quote will be placed round the next field (patient) in the final string.
2. The double quote matches the opening quote before the word insert, and closes that string.
3. The plus sign signifies that the previous and next strings should be concatenated together.
4. The str function ensures that the variable patient is returned as a string.
5. The double quote starts a new text string, which is the characters ','
6. The end of that string and the next variable follows.

If you replace the command mycursor.execute with print you will be able to see the result.
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

  Print Answers RSS
Top Experts
Last 24hrsThis month


CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900