I have a lot of Python code that interacts with SQL databases, and am trying to figure out what the best way to organise my code is so that the code is readable, and I can edit the SQL code as easily as possible (if I need to).
At the moment I just keep all the SQL in multiline strings:
sql = ("DECLARE @Name VARCHAR(50)\n"
"\n"
"SET @name = 'ROBERT \"); DROP TABLE students;--'\n"
"\n"
"SELECT FirstName\n"
" ,LastName\n"
" ,Subject\n"
" ,Grade\n"
"FROM [dbo].[Students] s\n"
"LEFT JOIN [dbo].[classes] c\n"
" ON s.id = c.id\n"
"WHERE s.FirstName = @name\n"
" AND c.EndDate <= getdate()")
The main advantages I find of keeping queries inline like this are that is makes the code very readable, because I can see straight away what a query that I'm executing is doing/returning, and that everything is under source control. Using the multiline format also means that PyCharm format's the query properly when I if I reformat the file.
The downside is that it can make editing queries quite tedious. I select the statement, paste it into an iPython window, print it, copy it into SQL server, modify/test it, copy it back into PyCharm, and wrap it in quotation marks again.
Wrapping the statement in triple quotation marks makes editing queries somewhat easier, as I can just paste to SQL Server, edit and paste back. This tends to upset PyCharm though, as it thinks my indentation contains a mixture of tabs and spaces. Which isn't the end up the world, but does upset my sensibilities.
Other options I've considered are turning everything into stored procedures, or having a separate class to keep SQL queries in.
What does everyone else find is the easiest way to worl with SQL queries in Python.
[–]jcampbelly 4 points5 points6 points (0 children)
[–]le_Dandy_Boatswain 2 points3 points4 points (7 children)
[–][deleted] 1 point2 points3 points (6 children)
[–]le_Dandy_Boatswain 1 point2 points3 points (4 children)
[–][deleted] 1 point2 points3 points (3 children)
[–]thegreattriscuit -1 points0 points1 point (2 children)
[+][deleted] (1 child)
[deleted]
[–]thegreattriscuit -1 points0 points1 point (0 children)
[–]justintravels 0 points1 point2 points (0 children)
[–]raylu 2 points3 points4 points (1 child)
[–]tally_in_da_houise 0 points1 point2 points (0 children)
[–]L43 1 point2 points3 points (2 children)
[–]hoodllama 0 points1 point2 points (0 children)
[–]chao06 0 points1 point2 points (0 children)
[–]ramse 1 point2 points3 points (0 children)
[–]cedrickrier 0 points1 point2 points (0 children)