1

Can someone explain why do I get an error when executing the following simple query with pandas:

import pyodbc
import pandas as pd

connstr = 'Driver={SQL Server}; Server=sr1; Database=db'
conn = pyodbc.connect(connstr)
query = """DECLARE @t AS DATETIME;
            SET @t = \'12-01-2020\';
            
            select top 10 AccountNumber
        FROM db.tb
          where ForecastDate >= @t"""


rt = pd.read_sql_query(conn, query)
conn.close()

ArgumentError: Could not parse rfc1738 URL from string 'DECLARE @t AS DATETIME;
            SET @t = '12-01-2020';

I understand that I can pass the variable t as a parameter to pandas and it will work, but I want to understand in principle what is causing the error, what are the restrictions on queries that can be passed to pandas. The query seems to work fine with cursor.execute(query).

4
  • 1
    Why do you need to declare? Simply pass date into where clause via iso format: 'YYYY-MM-DD'. Or pass as param from Python. Commented Dec 12, 2020 at 17:54
  • Yes, I can. I just want to understand what is the problem with the declaration in principle. Commented Dec 12, 2020 at 18:05
  • 2
    First argument of read_sql is SQL query string not connection object. Commented Dec 12, 2020 at 19:11
  • yes, not a smart mistake. Commented Dec 13, 2020 at 4:38

1 Answer 1

4

You passed the arguments to .read_sql_query() in the wrong order. You used

rt = pd.read_sql_query(conn, query)

when it should be

rt = pd.read_sql_query(query, conn)
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.