求助:pandas执行SQL查询时遭遇参数绑定错误(Error binding parameter 0 - probably unsupported type)
Hey there! Let's break down what's causing your error and fix it step by step.
First, let's identify the root issues:
Missing
ONclause for yourINNER JOIN
When joining two tables, you need to explicitly tell the database how they relate to each other. Your query doesn't have anONstatement to linkREAL_ESTATEandPRICEvia their sharedUNIQUE_RE_NUMBERcolumn—this is a critical syntax oversight.Incorrect parameter binding for a list of IDs
You're passing a list (IDs) to a single?placeholder, which only works for individual values. To query multiple IDs, you need to use theINoperator with a placeholder for each ID in your list.Missing
GROUP BYfor aggregated data
Since you're usingMAX(PRICE.UPDATE_DATE)(an aggregate function), you need to group your results by the non-aggregated columns in yourSELECTclause to avoid unexpected results or errors.
Here's the fixed code with explanations:
# Simplify getting IDs (no need for repeated DB queries if item.unqNum is valid) IDs = [item.unqNum for item in items] conn = sqlite3.connect('REDB.db') # Handle empty IDs case to avoid invalid SQL if not IDs: more_info = pd.DataFrame(columns=['UNIQUE_RE_NUMBER', 'MAX_DATE', 'RE_PRICE']) else: # Create placeholders for each ID (e.g., ?, ?, ? for 3 IDs) placeholders = ', '.join(['?' for _ in IDs]) # Fixed SQL: added JOIN condition, used IN for multiple IDs, added GROUP BY sql_query = f''' SELECT REAL_ESTATE.UNIQUE_RE_NUMBER, MAX(PRICE.UPDATE_DATE) AS MAX_DATE, PRICE.RE_PRICE FROM REAL_ESTATE INNER JOIN PRICE ON REAL_ESTATE.UNIQUE_RE_NUMBER = PRICE.UNIQUE_RE_NUMBER WHERE REAL_ESTATE.UNIQUE_RE_NUMBER IN ({placeholders}) GROUP BY REAL_ESTATE.UNIQUE_RE_NUMBER, PRICE.RE_PRICE ''' # Pass the IDs list directly as params (each ? maps to one ID) more_info = pd.read_sql_query(sql_query, conn, params=IDs) conn.close() print(more_info) return render_template("saved.html", items=items, more_info=more_info)
Key changes made:
- Simplified ID collection: Instead of querying the database for each ID individually, we directly extract
item.unqNuminto a list (you can keep the original check if you need to verify IDs exist inREAL_ESTATE, but this is more efficient). - Added
ONclause: LinksREAL_ESTATEandPRICEusing their sharedUNIQUE_RE_NUMBERcolumn, which is required for valid joins. - Dynamic placeholders: Generates a
?for each ID in your list, so the database knows to expect multiple values for theINclause. - Added
GROUP BY: Ensures theMAX(UPDATE_DATE)is calculated correctly per unique property and price entry. - Empty ID handling: Prevents invalid SQL if there are no saved items for the user.
内容的提问来源于stack exchange,提问作者Deesak

