1

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?

1 Answer 1

1

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

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

1 Comment

Thank you, I am actually reading sql query from file. I do not think formatting is the issue, since it runs find for just select statement.

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.