0

This might be a silly question. Is there a way to execute multiple queries in one execute statement?

cursor = conn.cursor()
cursor.execute("Select * from my_tables; show tables;")
result = cursor.fetchall()
7
  • 1
    No you can't do that, cursor.execute(sql, [params]) It takes one sql statement and params list (optional). Maybe you are looking for subqueries (MySQL Subqueries)? Commented Jun 17, 2013 at 13:38
  • you can always execute raw SQL statements like this: docs.djangoproject.com/en/dev/topics/db/sql Commented Jun 17, 2013 at 13:39
  • Thanks for the fast replies. The reason that i want to do this is because i am creating a sql injectable platform for class room purposes. So wiht cursore.execute(sql, [params]) will not work in that aspect. Do you know of any way that i can perform sql inject queries in python? Commented Jun 17, 2013 at 13:41
  • @user1817081 What DB API are you using? Commented Jun 17, 2013 at 13:49
  • @Aya i am using MySQLDB Commented Jun 17, 2013 at 13:50

1 Answer 1

1

Looks like the CLIENT_MULTI_STATEMENTS and CLIENT_MULTI_RESULTS options are enabled by default in MySQLdb (which is quite disturbing), so you can do something like this...

>>> import MySQLdb
>>> conn = MySQLdb.connect(db='test')
>>> cur = conn.cursor()
>>> cur.execute('select * from foo; show tables;')
2L
>>> cur.fetchall()
((1L,), (1L,))
>>> cur.nextset()
1
>>> cur.fetchall()
(('foo',),)

If you want to demonstrate an example which makes changes to an InnoDB table, you'll have to commit the transaction with something like...

>>> cur.execute('select * from foo; insert into foo values (123);')
2L
>>> cur.nextset()
1
>>> conn.commit()
>>> cur.execute('select * from foo')
3L
>>> cur.fetchall()
((1L,), (1L,), (123L,))

Check out PEP249 for the meaning of all the return values.

Sign up to request clarification or add additional context in comments.

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.