【问题标题】:Return results from Redshift database based on IF condition in Python根据 Python 中的 IF 条件从 Redshift 数据库返回结果
【发布时间】:2020-08-03 15:12:03
【问题描述】:

我需要根据用 Python 编写的 IF 条件从 redshift database 中提取结果。

假设我有一个表,CustomerID, SHipment Number, Invoice Station, ect 作为 Redshift table 中的列,如果客户 ID 存在,我想从 Redshift 表中获取所有记录,应该通过用户输入进行检查。

  • 表名 = ShipmentInfo
  • COLUMNS = CustomerID、BillNumber、发票站、费用等。

Python

import psycopg2

con=psycopg2.connect(dbname= 'datamodel', host='123', 
                     port= '5439', user= 'bce', password= 'Ciz')

cur = con.cursor()
HWB = input("Enter the House Bill Number : ")

#if CustomerID = HWB:
cur.execute("SELECT source_system, file_nbr, file_date, CustomerID 
             FROM public.shipment_info where CustomerID = $HWB")

results = cur.fetchall()

cur.close() 
con.close()

print(results)

【问题讨论】:

    标签: python sql postgresql amazon-redshift


    【解决方案1】:

    考虑用户输入值的参数化(否则冒着臭名昭著的风险,Bobby Tables)。

    # PREPARED STATEMENT WITH PLACEHOLDER
    sql = """SELECT source_system, file_nbr, file_date, CustomerID 
             FROM public.shipment_info 
             WHERE CustomerID = %s
          """
    
    # BIND PARAM VALUES WITH TUPLE OF ONE-ITEM
    cur.execute(sql, (HWB,))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-03-11
      • 2017-11-09
      • 2020-11-20
      • 1970-01-01
      • 2023-01-24
      相关资源
      最近更新 更多