如何将变量成功传递到sqlite SELECT语句?

时间:2019-01-03 14:05:41

标签: python python-3.x sqlite

我正在编写一个小程序,该程序可以让我通过资产号,序列号等搜索assets的sqlite数据库。问题是我不确定是否必须传递用户输入,变量{{ 1}},插入我的sqlite assetNum语句中。我希望它接受用户查询的SELECT并从sqlite表返回该行。

首先,我定义了我的函数:

assetNum

在程序中,我利用用户输入来浏览菜单,因此稍后在程序中,当我进入“按资产菜单搜索”时:

def search_asset_num(conn):

    cur = conn.cursor()
    cur.execute("SELECT * FROM assets WHERE AssetNumber = '{}'".format(assetNum))

    rows = cur.fetchall()

    for row in rows:
        print(row)

据我所知,问题是 elif selection == '2': menu2 = {} menu2[' 1'] = "Search Assets by Name" menu2[' 2'] = "Search Assets by Asset Number" menu2[' 3'] = "Search Assets by Serial Number" menu2[' 4'] = "Search Assets by Ownership" menu2[' 5'] = "Go back!" choices2 = menu2.keys() for entry in choices2: print(entry, menu2[entry]) selection2 = input("Enter number: ") if selection2 == '2': assetNum = input("Enter Asset Number: ") search_asset_num(conn) 存在于assetNum函数的上方,而该函数实际上在search_asset_num()语句中被定义为if。我不确定如何解决此问题。我曾尝试在代码的顶部使assetNum = input("Enter Asset Number: ")成为全局变量,并将其设置为等于assetNum作为占位符,但这没有用。它仅将0输出到终端。

1 个答案:

答案 0 :(得分:2)

assetNum添加为函数的参数,

def search_asset_num(conn, assetNum):
    cur = conn.cursor()
    cur.execute("SELECT * FROM assets WHERE AssetNumber = ?", (assetNum,))
    rows = cur.fetchall()
    for row in rows:
        print(row)

在菜单中,您可以进行以下更改:

        if selection2 == '2':
            assetNum = input("Enter Asset Number: ")
            search_asset_num(conn, assetNum)

还使用Python sqlite3 - DB-API documentation

中所述的“参数替换”