简体   繁体   中英

Cannot declare date variable in correct format for sql query in Python

Executing an sql query using Python and feeding in a date variable for the select. But I am getting the error 'datetime2 is incompatible with int (206)' I have mucked around with the variable but can't seem to get it into the correct format. Code below:

import pyodbc
import pandas as pd
import datetime

dt = datetime.date(2021, 10, 1)
print (dt)

server = 'testServer'
database = 'testDatabase'
username = 'test'
password = '{test}'   
driver= '{ODBC Driver 13 for SQL Server}'

conn = pyodbc.connect('DRIVER='+driver+';SERVER=tcp:'+server+';PORT=1433;DATABASE='+database+';UID='+username+';PWD='+ password)

conn.autocommit = True

select_sql = """Select * From test Where Inception <= {x}""".format(x=dt)

sql_query = pd.read_sql_query(select_sql, conn)

Pointed significantly in the right direction by @shahkalpesh (thank you), using this parametrization solved the issue with the date. """Select * From test Where Inception <= ?""" sql_query = pd.read_sql_query(select_sql, conn, params=[dt])

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