How to use .format() string in a MySQL statement? - python

I'm trying to format a MySQL statement with today's data, as well as 7 days back. I'm pretty sure the date is in the correct format, so I don't think that's the issue.
The error report is:
Warning: (1292, "Incorrect datetime value: '{} 16:00:00' for column 'run_start_date' at row 1")
result = self._query(query)
Traceback (most recent call last):
AttributeError: 'int' object has no attribute 'format'
e.g.
today = DT.date.today()
week_ago = today - DT.timedelta(days=7)
print(today.strftime('%Y-%m-%d'))
print(week_ago.strftime('%Y-%m-%d'))
cursor.execute(SELECT * FROM db WHERE run_start_date BETWEEN '{} 16:00:00' AND '{} 16:00:00'format(week_ago, today)

Using prepared statements (safe way):
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])
Using .format() which leaves you at risk for sql injections (if you pass user input to .format() e.g.)
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)

Related

How to update data through "UPDATE TABLE SET COL1 = %s WHERE COL2=%s", using mysql.connect, python

import mysql.connector as mc
USER = ''
PASSWORD = ''
HOST = ''
DATABASE = ''
mydb = mc.connect(user=USER, password=PASSWORD, host=HOST, database=DATABASE)
print(mydb.get_server_info())
mycursor = mydb.cursor()
### Let's just say "len(list_example_01) = len(list_example_02)"
### and "len(rows)" (SELECT column01_name FROM table_name WHERE DATE > DATE_FORMAT(CURDATE(), '%Y-%m-%d %H:%m:%s') also same.
data_example = []
for idz, i in enumerate(list_example_01):
data_example.append((i, list_example_02[idz]))
sql = '''
UPDATE table_name SET column01_name = %s WHERE column02_name = %s AND DATE > DATE_FORMAT(CURDATE(), '%Y-%m-%d %H:%m:%s')
'''
mycursor.executemany(sql, data_example)
mydb.commit()
I am a beginner to mysql and python. I try to update value01 into column01 WHERE column02_name = list_example02[idz].
Following just show what i try to make...... e.i:
CPUNAME
IMG_PATH
DATE
I5-11400
http://bcd/~~
2021-04-30 15:00:00
I5-10900
http://abcd/~~
2021-04-30 15:00:00
more...
I have list.
list_example_02 = ["I5-11400", "I5-10900", "I5-10400", ... ]
I want to find the row (which has same "cpu name" in list).
And I want to update "IMG_PATH" column's value.
01_Run
UPDATE CPU_TABLE SET IMG_PATH = 'http://bcd/~~' WHERE CPUNAME = 'I5-11400' AND DATE > DATE_FORMAT(CURDATE(), '%Y-%m-%d %H:%m:%s')
02_Run
UPDATE CPU_TABLE SET IMG_PATH = 'http://abcd/~~' WHERE CPUNAME = 'I5-10900' AND DATE > DATE_FORMAT(CURDATE(), '%Y-%m-%d %H:%m:%s')
i try to make loop (01_RUN, 02_RUN, ...) with 2var (1 var is for searching, and choosing specific row, and other Var is for Value.)
But...... when i run script above, i met "error message"
Traceback (most recent call last):
File "\venv\lib\site-packages\mysql\connector\cursor.py", line 75, in call
return bytes(self.params[index])
IndexError: tuple index out of range
As above written, Tuple has 2 element and there are 2 placeholder (%s) in preparedstatement. But I got error - Index out of range -.
This is the question which i have.
how to fix this?
"Thank you in advance"
It makes no sense to Format curdate() as it has already that format you want
Do that instead, and avouid the problem altogether with the %s and dateformat
UPDATE CPU_TABLE SET IMG_PATH = 'https://bcd/~~' WHERE CPUNAME = 'I5-11400' AND DATE > CURDATE();

How to insert today's date in SQL select statement using python?

I'm trying to send today variable into SQL but it is not working.
import datetime from date
today = date.today()
stmt = "select agent_email from customer_interaction_fact where to_date(DT) >= + today + ORDER BY CONVERSATION_CREATED_TIME DESC"
You don't have to compute today's date in Python. Just use the PostgreSQL function CURRENT_DATE:
stmt = "SELECT ... WHERE TO_DATE(DT) >= CURRENT_DATE ..."
What database engine you're using? You'd need to convert the python datetime object into string with format accepted by the database.
# In case YYYY-MM-DD
today_str = str(today)
stmt = f"""select agent_email
from customer_interaction_fact
where to_date(DT) >= datetime({today}, "YYYY-MM-DD")
order by CONVERSATION_CREATED_TIME DESC"""
Another solution, assuming the client (your program) is in the same timezone as the database engine, you could use your database engine datetime.now function. In SQLite for instance datetime('now')
try like below
from datetime import date
today = date.today()
stmt = "select agent_email,aht_in_secs,queueid,EFFORTSCORE from facts.public.customer_interaction_fact where agent_email <> 'Bot' and aht_in_secs is not NULL and to_date(DT) >=" + today + "ORDER BY CONVERSATION_CREATED_TIME DESC"

How do i convert List into datetime.date object?

I'm trying to extract data from my db and display it in a well formatted form.
When db gives me the date i'm trying to display it in the form of String 'Day/Mon/Year'. I have used the following code to do so , but it is throwing me the error.
How do i convert a list to date.time object ?
import psycopg2
from datetime import datetime
db = psycopg2.connect("dbname=news")
if db:
print("DB CONNECTED")
c = db.cursor()
c.execute("select day from (select date(time) as day, count(id) as errors from log where status != '200 OK' group by day order by errors desc limit 1) as seq")
t = c.fetchall()
res = datetime.strftime(t,'%b %d, %Y')
print(res)
db.close()
TypeError: descriptor 'strftime' requires a 'datetime.date' object but received a 'list'
From my experience you need to iterate over the list. maybe this wil work, havent tested it, but thats the way i do it.
import psycopg2
from datetime import datetime
db = psycopg2.connect("dbname=news")
if db:
print("DB CONNECTED")
c = db.cursor()
c.execute("select day from (select date(time) as day, count(id) as errors from log where status != '200 OK' group by day order by errors desc limit 1) as seq")
t = c.fetchall()
c.close()
db.close()
for dates in t:
print(datetime.strftime(dates, '%b %d, %Y'))

Get results from MySQL statement and store in Python list and checking conditions

I have a Python list "table_list" which has MySQL data tables names. I need to "start_time" field values from 1st data table and store in another list "file_sTimeList" after converting to datetime.
from datetime import datetime, timedelta
sq = """SELECT start_time FROM %s""" % (table_list[0])
cursor.execute(sq)
result = cursor.fetchall()
file_sTimeList = []
for row in result:
file_sTime = f'{row[0]:%Y-%m-%d %H:%M:%S%z}'
file_sTimeList.append(file_sTime)
# print("file_sTime: ", file_sTimeList)
Then I get current server time - 24 hours time.
# get current server time
tz_PP = pytz.timezone('Asia/Phnom_Penh')
serverTime = datetime.now(tz_PP).strftime("%H:%M:%S")
print("serverTime: ", serverTime)
# get 24 hours - current server time
st_24hrs = datetime.now(tz_PP) - timedelta(hours=24)
serverTime_24hrs = st_24hrs.strftime('%Y-%m-%d %H:%M:%S')
print("serverTime_24hrs: ", serverTime_24hrs)
And finally I check each item from my previous list "file_sTimeList", if it exceeds 24hrs time and if so delete data.
# Clear DB all records , if exceed 24hrs
for st in file_sTimeList:
if serverTime_24hrs > st:
print("Exceed 24 hours")
try:
import datetime
for r in range(len(table_list)):
sql_1 = f"""DELETE FROM %s WHERE start_time = '{datetime.datetime.strptime(file_sTime, '%Y-%m-%d %H:%M:%S')}'""" \
% (table_list[r])
cursor.execute(sql_1)
print("DB clean")
except Exception as e:
print("Error: ", e)
raise e
else:
print("24 time")
However this doesn't give me correct output. What am I doing wrong here?
Any help is appreciated. Thanks.
What if you create a datetime object for each element in the query instead of an f-string.
from datetime import datetime, timedelta
sq = """SELECT start_time FROM %s""" % (table_list[0])
cursor.execute(sq)
result = cursor.fetchall()
file_sTimeList = []
for row in result:
# Create a datetime instead of having a string
file_sTime = datetime.strptime(f'{row[0]:%Y-%m-%d %H:%M:%S%z}')
file_sTimeList.append(file_sTime)
With that modification, it should work.

SQLite received a naive datetime while time zone support is active

I'm getting the following error while running my sql in python
/usr/lib/python2.6/site-packages/django/db/backends/mysql/base.py:64: RuntimeWarning: SQLite received a naive datetime (2012-06-22 15:53:43) while time zone support is active.
my query also returns the wrong data.
if i change the time up 2 hours (17:53:43 instead of 15:53:43), my timezone atm is gmt +2 so i think the problem is in the time zone.
how do i change my query to make the sql execute in the way i intend it to?
sql:
sqlQuery = """SELECT w.id, w.serial, w.finishdate, w.weighingtype_id, w.netto, w.bruto, w.deleted
FROM weighing w
LEFT JOIN weighing w1
ON w1.id = w.parent_id
WHERE w.user_id = %(userid)s"""
if date:
sqlQuery = sqlQuery + " AND (w.created = %(date)s OR w.modified > %(date)s)"
edit: added my code for transforming the datetime
data = request.GET.copy()
if 'date' in data:
try:
data['date'] = datetime.datetime.strptime(data['date'], "%Y-%m-%dT%H:%M:%S")
except:
raise error(311)

Categories