我可以将 sqlite3 表列名作为搜索参数传递吗?



我在堆栈溢出上的第一个帮助请求。蟒蛇版本 3.6.4

我的代码有问题。它旨在根据输入的参数返回报价 - 例如国家/地区、货件重量以及给定国家/地区的城市所在区域。

表格看起来像这样(Excel图片(。 截图图片 是否可以缩小使用哪一列的范围。例如,如果搜索参数是爱沙尼亚和 3 公斤,它会很好地返回区域 1、区域 2 和区域 3 的所有三列:

What country? :estonia
weight?: 70
('estonia', '75', '10,83', '12,25', '14,43')

但是,我可以根据用户输入传入参数以缩小用于获取值的区域列的范围吗?

例如,如果城市位于 zone1 中,则根据其他搜索参数仅从 zone1 列中获取值

我的健壮代码如下:

import sqlite3
import pandas as pd
conn = sqlite3.connect("transportHinnakiri.db")
c = conn.cursor()
df = pd.read_csv("baltikum.csv")
df.to_sql("baltikum", conn, if_exists="append", index=False)
input_country = input("What country? :").lower()
input_weight = int(input("Weight?: "))
def weight_category(input_weight):
if input_weight < 1:
return 1
elif 1 < input_weight <= 3:
return 3
elif 3 < input_weight <= 10:
return 10
elif 10 < input_weight <= 20:
return 20
elif 20 < input_weight <= 31.5:
return 31.5
elif 31.5 < input_weight <= 50:
return 50
elif 50 < input_weight <= 75:
return 75
elif 75 < input_weight <= 100:
return 100
result = weight_category(input_weight)
def get_post():
c.execute("SELECT * FROM baltikum WHERE country=? AND weight=?",(input_country, result))
row = c.fetchone()
return row
result_final = get_post()
print(result_final)`

我不确定这是否是您要找的,但这是我的做法。首先从用户那里获取城市:

city = input("input City: ").lower()

然后我会创建一些数据结构,比如字典,其中包含所有区域及其城市:

zones = {'zone1': ['boston', 'new york'], 'zone2': ['san fransisco', 'los 
angeles']}

然后你可以有一个函数,它接收一个城市并返回一个区域

def get_zone(city):
for zone in zones.keys():
if city in zones[zone]:
return zone
return "Error city not found"

当然,您必须做一些事情来规范用户输入。然后,您可以创建一个命令字符串并执行该命令

def execute_command(zone, weight, country):
cmd = "SELECT {zone} FROM baltikum WHERE country={country} AND weight={weight}".format(zone = zone, country = country, weight = weight)
data = c.execute(cmd)
return data

然后,您仅从所选区域获取数据。希望这有帮助!

最新更新