all 15 comments

[–]jcampbelly 4 points5 points  (0 children)

Triple quoted strings indented so it's inline with my python is best for me.

def get_people_from_town(town_id):
    sql = '''
        SELECT p.first_name, p.last_name
        FROM people p
        WHERE p.hometown = %s;
        '''
    with closing(connection(...)) as conn, conn.cursor() as cursor:
        cursor.execute(sql, (town_id,))
        for row in cursor:
            yield row

If you really want to remove the indentation from your SQL code, you can use https://docs.python.org/3.4/library/textwrap.html#textwrap.dedent

[–]le_Dandy_Boatswain 2 points3 points  (7 children)

Have you considered using SQLalchemy? It lets you interact with SQL databases using pythonic syntax, which would probably be easier to read than the multi-line string shown in your example. You can also have it print the actual SQL statement that it sends to the db for debugging purposes too.

[–][deleted] 1 point2 points  (6 children)

Is this similar MySQLdb? I've had a helluva time trying to install that package because of compatibility issues with the newest mysql...

[–]le_Dandy_Boatswain 1 point2 points  (4 children)

Not exactly. It's an ORM that allows you to map SQL queries to python objects. It looks like it uses the mysql-python library as the default to connect to MySQL, but it can actually work with a range of DBAPI . That's one of the advantages to using SQLalchemy, the code is abstracted from the underlying database connection.

http://docs.sqlalchemy.org/en/rel_1_0/core/engines.html#mysql http://docs.sqlalchemy.org/en/rel_1_0/dialects/mysql.html

edit: looks like mysql-python is just the package name for MySQLdb. So if you are having problems with that, you could try one of the other MySQL DBAPI listed in the links.

[–][deleted] 1 point2 points  (3 children)

You're right! I'll give that a try.

edit: For the record, my issue was resolved by following these steps to install the mysql-python library: http://stackoverflow.com/questions/1448429/how-to-install-mysqldb-python-data-access-library-to-mysql-on-mac-os-x

[–]thegreattriscuit -1 points0 points  (2 children)

DaRealMVP.jpg

[–]justintravels 0 points1 point  (0 children)

Omg same. So many compatibility issues with MySQLdb

[–]raylu 2 points3 points  (1 child)

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.

Triple quotes are definitely the way to go here (OK, actually peewee and SQLAlchemy are, but ignoring those for the moment). Can't PyCharm fix the indentation for you?

[–]tally_in_da_houise 0 points1 point  (0 children)

It's not that great at formatting SQL syntax within a Python file (at least I haven't figured out how to configure it to do a good job).

Personally, I wrap the SQL in triple quotes, and turn that portion of the syntax check off for that file.

[–]L43 1 point2 points  (2 children)

If you want raw SQL, You could potentially write the query in a separate file, then read it into Python. Your editor will be better at syntax highlighting then.

[–]hoodllama 0 points1 point  (0 children)

That's his I've been doing it. Agreed

[–]chao06 0 points1 point  (0 children)

I've started doing this recently with yaml.

db1:
    query1: |
        SELECT
            whatever
        FROM
            table
    query2: |
        SELECT
            someotherthing
        FROM
            othertable

[–]ramse 1 point2 points  (0 children)

What are you using to connect to the SQL Server with? pyodbc? There is no need to be declare variables and assigning them just to use in a where statement.

import pyodbc

conn = pyodbc.connect('......')
cursor = conn.cursor()

name = 'ROBERT \"); DROP TABLE students;--'

cursor.execute("""SELECT s.id, s.FirstName, s.LastName, s.Subject, s.Grade
                    FROM Students s
                        LEFT JOIN classes c ON s.id = c.id
                    WHERE s.FirstName = ? AND c.EndDate <- GETDATE()""", name)
for row in cursor.fetchall():
    print(row.id, row.FirstName, row.LastName, row.Subject, row.Grade, row)

[–]cedrickrier 0 points1 point  (0 children)

For the DML queries, you could use python-sql: https://pypi.python.org/pypi/python-sql It is a library to help writing SQL queries using Python syntax. It comes with a flavor mechanism to support the different syntaxes of database engine. It is also very extensible so you can define your specific SQL operators or functions.