简体   繁体   中英

How to use a variable from a loop multiple times in a sql statement in Python

I've got a list in pandas that I want to iterate through, and for each item in the list, apply it to multiple components of a SQL query

Below is what I've been trying to work with, but I don't get anything back in the results, which makes me think that the variables aren't populating correctly.

If I run the SQL query outside of python, with a single hardcoded value, it works.

What am I missing?

import teradata
import pandas as pd
import numpy as np
import datetime

start_date = "2017-10-28"
stop_date = "2017-10-30"
mydates = pd.date_range(start_date, stop_date, format='%Y-%d-%m')
date_list = [d.strftime('%Y-%m-%d') for d in mydates]

data = []

for x in date_list:
    for row in session.execute("""
    select distinct CAST(? as DATE)as dateId, count(*) 
    FROM tableA
    where last_date>=?-365 and first_date>=?-360
    group by 1""", (x, x, x, )):
        data.append(row)

You cannot use a parameter placeholder, ? , in any numeric operations, + - * / , and the same for string operations (ie, concatenating wildcards operators to LIKE expressions).

Therefore, simply run your operations before binding values to prepared statement in the params argument of con.execute or cursor.execute . Also, the comma ending inside a tuple is not needed for multiple items only for one-item tuples.

import datetime as dt

start_date = dt.datetime.strptime("2017-10-28", '%Y-%m-%d')
stop_date = dt.datetime.strptime("2017-10-30", '%Y-%m-%d')

rng = (stop_date - start_date).days

date_list = [(start_date + dt.timedelta(days=i)).strftime(format='%Y-%m-%d')  
             for i in range(rng+1)]    
last_date_list = [(start_date + dt.timedelta(days=i+365)).strftime(format='%Y-%m-%d')  
                  for i in range(rng+1)]    
first_date_list = [(start_date + dt.timedelta(days=i+360)).strftime(format='%Y-%m-%d')  
                   for i in range(rng+1)]

strSQL = """select distinct CAST(? as date format 'YYYY-MM-DD') as dateId, count(*) 
            from tableA
            where last_date >= cast(? as date format 'YYYY-MM-DD') 
              and first_date >= cast(? as date format 'YYYY-MM-DD')
            group by 1"""

for x, l, f in zip(date_list, last_date_list, first_date_list):
    for row in session.execute(strSQL, (x, l, f)):
        data.append(row)

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