You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Flask调用utils.py中SQLite查询函数报参数类型不支持错误

解决Flask接口调用SQLite时的参数绑定错误

核心问题排查与解决步骤

1. 统一参数类型转换

Flask POST请求接收的参数默认是字符串,若数据库中seat_no为整数类型,直接传递会触发类型不匹配错误。在接口层先做类型校验与转换:

# app.py 中的接口实现
from utils import getResultData
from flask import request, jsonify

@app.route('/query-result', methods=['POST'])
def query_result():
    seat_no = request.form.get('seat_no')
    # 转换为整数(适配数据库字段类型)
    try:
        seat_no = int(seat_no)
    except ValueError:
        return jsonify({"error": "seat_no必须为整数"}), 400
    result = getResultData(seat_no)
    return jsonify(result)

2. 用绝对路径连接数据库

utils.py与app.py的运行工作目录可能不同,导致数据库文件路径解析异常,间接引发参数绑定问题。修改utils.py中的数据库连接逻辑:

# utils.py 中的查询函数
import sqlite3
import os

def getResultData(seat_no):
    # 获取当前脚本所在目录的绝对路径,拼接数据库文件路径
    db_dir = os.path.dirname(os.path.abspath(__file__))
    db_path = os.path.join(db_dir, 'BE.db')
    conn = sqlite3.connect(db_path)
    cursor = conn.cursor()
    # 严格使用参数化查询
    cursor.execute("SELECT * FROM result WHERE seat_no = ?", (seat_no,))
    data = cursor.fetchall()
    conn.close()
    return data

3. 禁止用f-string拼接SQL

f-string格式化SQL会破坏参数类型处理逻辑,还存在SQL注入风险,必须使用SQLite原生的参数化查询语法:

  • 错误写法(请勿使用):
cursor.execute(f"SELECT * FROM result WHERE seat_no = {seat_no}")
  • 正确写法:
cursor.execute("SELECT * FROM result WHERE seat_no = ?", (seat_no,))

4. 检查参数传递格式

确保调用getResultData时传递的是单个值,而非列表、字典等其他类型:

  • 错误示例:
# 错误:传递了列表而非单个参数
result = getResultData([seat_no])
  • 正确示例:
# 正确:传递单个参数
result = getResultData(seat_no)

内容的提问来源于stack exchange,提问作者mizerable

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.19 09:47:57