3

I could write a SP inside Mysql and excute with a call statement. But looking to write it in python instead. I got stuck with using sql script on multiple lines.

conn = pyodbc.connect('DSN=MySQL;PWD=xxxx') 
csr = conn.cursor()

Sql= 'SELECT something, something 
    FROM table 
    WHERE foo=bar 
    ORDER BY foo '

csr.execute(Sql)
sqld = csr.fetchall()
2
  • 8
    Put the text in triple quotes - that way it doesn't give you a syntax error because of the linebreaks. Commented Jan 25, 2011 at 18:12
  • 1
    @Shadikka: Please post your answer as an answer, not a comment. We can't give you credit if it's only a comment. Commented Jan 25, 2011 at 18:17

2 Answers 2

2

Heh, I don't mind to make it a proper answer.

String literals in triple quotes can include linebreaks and won't cause syntax errors. Otherwise (with "string" or 'string') you will need to include a backslash before every linebreak to make it work. And from experience, that's easy to screw up. :)

As a minor note, in Python variables are usually started with a lowercase letter, names starting with capital letters usually being given to classes.

So:

Sql = """SELECT something, something 
         FROM table 
         WHERE foo=bar 
         ORDER BY foo"""
Sign up to request clarification or add additional context in comments.

1 Comment

Any idea how to do """Truncate table2; Select * from table1;""". Using double ; within a csr.execute(Sql)...causes a prob
2

If you don't mind the overhead, take a look at sqlalchemy:

SQLAlchemy is the Python SQL toolkit and Object Relational Mapper that gives application developers the full power and flexibility of SQL.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.