簡體   English   中英

我可以將sqlite3表列名作為搜索參數傳遞嗎?

[英]Can I pass sqlite3 table column name as search parameter?

我對堆棧溢出的第一個幫助請求。 Python版本3.6.4

我的代碼有問題。 它旨在根據輸入的參數(例如國家/地區,貨運重量以及給定國家/地區的城市)返回報價。

該表看起來像這樣(excel圖片)。 屏幕快照圖像可以縮小要使用的列的范圍。 例如,如果搜索參數是愛沙尼亞和3公斤,則可以很好地返回zone1,zone2和zone3的所有三列:

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

然后,您只能從選定區域中獲取數據。 希望這可以幫助!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM