sql >> Database teknologi >  >> RDS >> Mysql

Hvordan bruger man .format()-strengen i en MySQL-sætning?

Brug af forberedte udsagn (sikker måde):

qry = """
    SELECT *
    FROM db
    WHERE run_start_date BETWEEN '%s 16:00:00' AND '%s 16:00:00'
""" # 

today = DT.date.today()
week_ago = today - DT.timedelta(days=7)
today = str(today.strftime('%Y-%m-%d'))  # Convert to string
week_ago = str(week_ago.strftime('%Y-%m-%d'))  # Convert to string

cursor.execute(qry, [today, week_ago])

Brug af .format(), som giver dig risiko for sql-injektioner (hvis du f.eks. sender brugerinput til .format())

qry = """
    SELECT *
    FROM db
    WHERE run_start_date BETWEEN '{today} 16:00:00' AND '{week_ago} 16:00:00'
""" # Use named placeholders, nicer to read, prevents you having to repeat variables multiple time when calling .format()

today = DT.date.today()
week_ago = today - DT.timedelta(days=7)
today = str(today.strftime('%Y-%m-%d'))  # Convert to string
week_ago = str(week_ago.strftime('%Y-%m-%d'))  # Convert to string

qry = qry.format(today=today, week_ago=week_ago)
cursor.execute(qry)



  1. MySQL trigger sæt værdier for NY række og opdatere en anden i samme tabel

  2. SQL-forespørgsler

  3. Hvordan gemmer man en liste over hverdage i MySQL?

  4. PostgreSQL videregiver data fra rekursiv CTE til funktion