Merlin
Merlin

Reputation: 25639

How to use for loops to do multiple SQL statements in python

I have SQl statement List, when running the a single statement it work running the loop it gives:

pyodbc.ProgrammingError: ('42000', "[42000] [MySQL][ODBC 5.1 Driver][mysqld-5.5.8]You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'Sql_2' at line 1 (1064) (SQLExecDirectW)")

SQl = """Select something"""
    SQl_2 = """Select something"""
    SQl_3 = """Select something"""


Sqls= ('Sql','Sql_2','Sql_3')

for x in Sqls:
    print x
    use = Sql_2  
    # use = x
    cxn = pyodbc.connect('DSN=MySQL;PWD=xxx') 
    csr = cxn.cursor()
    csr.execute(use)
    fetch = csr.fetchall()

Upvotes: 0

Views: 5397

Answers (2)

Michal Chruszcz
Michal Chruszcz

Reputation: 2490

You should additionally move connecting to the database as well as creating a cursor out of the for-loop, since it's unneeded overhead.

SQl = """Select something"""
SQl_2 = """Select something"""
SQl_3 = """Select something"""

Sqls = (Sql, Sql_2, Sql_3)
cxn = pyodbc.connect('DSN=MySQL;PWD=xxx') 
csr = cxn.cursor()

for x in Sqls:
    print x
    use = Sql_2  
    # use = x    
    csr.execute(use)
    fetch = csr.fetchall()

Upvotes: 3

Sven Marnach
Sven Marnach

Reputation: 601559

Your tuple should be

Sqls = (Sql,Sql_2,Sql_3)

instead of

Sqls = ('Sql','Sql_2','Sql_3')

Upvotes: 6

Related Questions