简体   繁体   中英

Error executing complex sql query with Python

I have the following query:

sql_query = 'DROP TABLE IF EXISTS #temp1

select top 100 * 
into #temp1
from some_table_A

select top 100 * from #temp1'

When I try to run it with:

conn_obj = some_function_to_create_conn_obj()
cs = conn_obj.cursor()
data = cs.execute(sql_query).fetchall()

conn_obj.close()

I end up with error:

Traceback (most recent call last):
  File "C:\Users\some_user\Anaconda3\envs\env1\lib\site-packages\IPython\core\interactiveshell.py", line 3397, in run_code
    exec(code_obj, self.user_global_ns, self.user_ns)
  File "<ipython-input-26-d6279d5d7e78>", line 1, in <cell line: 1>
    data = cs.execute(sql_query).fetchall()
pyodbc.ProgrammingError: No results.  Previous SQL was not a query.

I also get error if I try to execute it with:

import pandas as pd
df = pd.read_sql_query(sql_query, conn_obj)


Traceback (most recent call last):
  File "C:\Users\some_user\Anaconda3\envs\env1\lib\site-packages\IPython\core\interactiveshell.py", line 3397, in run_code
    exec(code_obj, self.user_global_ns, self.user_ns)
  File "<ipython-input-30-59174146dbd6>", line 1, in <cell line: 1>
    df = pd.read_sql_query(sql_query, conn_obj)
  File "C:\Users\some_user\Anaconda3\envs\env1\lib\site-packages\pandas\io\sql.py", line 436, in read_sql_query
    return pandas_sql.read_query(
  File "C:\Users\some_user\Anaconda3\envs\env1\lib\site-packages\pandas\io\sql.py", line 2117, in read_query
    columns = [col_desc[0] for col_desc in cursor.description]
TypeError: 'NoneType' object is not iterable

This is probably due to SQL insert statement. Simple select queries are running fine. Is there a work around?

The problem that you have is because you are using ' to start and close a string with multiple lines.

There's a answer for that

Python SQL query string formatting

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM