模拟外部最终用户对 SQL 数据库的 API 调用

simulating an API call by an external end user to an SQL Database

此脚本使用 JSON 输入作为参数,并且应该是来自命令行的 运行。一个例子 可能是 运行 作为: python count_stock.py '{"productId":1}' return 是哪个值 [(9,)] 我需要编写一个脚本,利用 count_stock.py 到 return 进一步的机密信息 数据库。新脚本不得直接与数据库通信,只能调用 count_stock.py

这是count_stock.py脚本

import sys, sqlite3, json
company_db_file = 'company_data.db'
conn = sqlite3.connect(company_db_file)
c = conn.cursor()
for arg in sys.argv[1:]:
    input_json = json.loads(arg)
    c.execute("SELECT amount FROM product WHERE id = " + str(input_json['productId']))
    sys.stdout.write(str(c.fetchall())+ "\n")
conn.commit()
conn.close()

str 函数似乎没有在参数两边加上引号,因此您可以在命令行中传递您想要的任何 SQL。例如...

python count_stock.py '{"productId":"1 or 1 = 1"}'

这应该执行这个 SQL:

SELECT amount FROM product WHERE id = 1 or 1 = 1

此查询忽略 "ID" 过滤器和 returns table 中的所有行。