Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PyMySQL unable to execute multiple queries

Using the latest version of PyMySQL(0.9.3) I am unable to execute a query string which has multiple SQL statements in it separated by a semicolon(;)

My python version is: Python 3.6.5

import pymysql # version 0.9.3
conn = {
    "host": "mysql_server_hostname",
    "password": "my_password",
    "port": <<port_no>>,
    "user": "my_username"
}

my_query_str = 'show databases;use random_existing_db;'
with pymysql.connect(**conn):
    cur.execute(query)

Error returned: (1064, 'Multiple statements detected in a single query)

Tried running the same query with PyMySQL-0.7.11 and it works

like image 605
Saif S Avatar asked Oct 24 '19 15:10

Saif S


People also ask

Can a cursor execute multiple queries?

Executing multiple queries with execute() By default, it is set to False . If set to True , allows execute() to execute multiple queries separated by semicolons. When called with multi=True , the execute() method returns an iterator which can be used to access the result set produced by the queries.

How do you run a query in Python?

Use the cursor to execute a query by calling its execute() method. Use fetchone() , fetchmany() or fetchall() method to fetch data from the result set. Close the cursor as well as the database connection by calling the close() method of the corresponding object.


2 Answers

In pymysql version 0.8 onwards client flag is no longer set by default. For executing multiple statements one needs to pass client_flag=CLIENT.MULTI_STATEMENTS.

reference: https://github.com/PyMySQL/PyMySQL/blob/v0.9.3/CHANGELOG#L66

Example of the fix below.

import pymysql
from pymysql.constants import CLIENT

conn = {
    "host": "mysql_server_hostname",
    "password": "my_password",
    "port": <<port_no>>,
    "user": "my_username",
    "client_flag": CLIENT.MULTI_STATEMENTS
}

my_query_str = 'show databases;use random_existing_db;'
with pymysql.connect(**conn) as cur:
    cur.execute(my_query_str)
like image 88
Saif S Avatar answered Oct 25 '22 16:10

Saif S


That's right, I used the client_flag = CLIENT.MULTI_STATEMENTS parameter to take effect.

like image 41
Zhou Avatar answered Oct 25 '22 17:10

Zhou