I have a problem with my code python, i'm using Pandasql, and what i want is to use my (enddate) in a query so:
enddate = pd.to_datetime(datetime.today()).date()
q2 = """SELECT * FROM res_q1 t1 where t1.JOURS = (enddate) """
res_q2 = psql.sqldf(q2, locals())
Can you help me plz!!!
You can add it with formatting, e.g.
from datetime import datetime
end_date = pd.to_datetime(datetime.today()).date()
q2 = """SELECT * FROM res_q1 t1 where t1.JOURS = ({}) """.format(end_date)
res_q2 = psql.sqldf(q2, locals())
Hope this helps :)
Related
I'm using cx_Oracle and I'm trying to bind a date variable value inside SQL but I'm not able the resolve the errors. Can someone please offer insight on how to fix it?
The code below gives me an error: "DatabaseError: ORA-00936: missing expression"
dat_ptd_sql = """
select
univ_prop_id,
chain_id
from BA4DBOP1.zs_ptd_stack
where chain_ord = 1
and sale_valtn_dt >= date :cu_perf_beg
"""
cudb_cur.execute(dat_ptd_sql, cu_perf_beg = "'2022-09-01'")
Another option is to use an actual date inside Python:
import datetime
dat_ptd_sql = """
select
univ_prop_id,
chain_id
from BA4DBOP1.zs_ptd_stack
where chain_ord = 1
and sale_valtn_dt >= date :cu_perf_beg
"""
cudb_cur.execute(dat_ptd_sql, cu_perf_beg = datetime.datetime(2022, 9, 1))
Try something like this. Note the to_date(). This example uses python-oracledb, which is the new name for the latest version of cx_Oracle.
import getpass
import os
import oracledb
un = os.environ.get('PYTHON_USERNAME')
cs = os.environ.get('PYTHON_CONNECTSTRING')
pw = getpass.getpass(f'Enter password for {un}#{cs}: ')
connection = oracledb.connect(user=un, password=pw, dsn=cs)
with connection.cursor() as cursor:
sql = """select
ename
from emp
where empno = 7654
and hiredate >= to_date(:bv, 'YYYY-MM-DD')"""
for r in cursor.execute(sql, bv='1981-04-01'):
print(r)
I have 2 variables: datetime.date and datetime.datetime
import sqlite3
from datetime import date
#bot.message_handler(commands=['check'])
def start_message(message):
cursor = conn.execute("SELECT * from DATA WHERE id = ? ORDER BY DATE ", (message.from_user.id,))
row = cursor.fetchone() #datetime.datetime
datee = date.today() #datetime.date
print(datee - parse(row[2]).date())
bot.send_message(message.chat.id, row[1])
bot.send_message(message.chat.id, str(datee - parse(row[2])))
print is displaying -1 day, 0:00:00, but I need to take out the timestamp. How can I do it?
If you only want to print the days (without the hours,minutes,seconds), you can use the attribute.days, e.g.:
print((datee - parse(row[2]).date()).days)
this works because what you receive is not a date object anymore but a datetime.timedelta object.
I've a script that makes a query to my database on MySQL. And my doubt is if I can pass any parameter to that query through Python.
For example, on the following script I want to calculate the date_filter using Python and then apply that filter on the query.
now = dt.datetime.now()
date_filter = now - timedelta(days=3)
dq_connection = mysql.connector.connect(user='user', password='pass', host='localhost', database='db')
engine = create_engine('localhost/db')
cursor = connection.cursor(buffered=True)
query = ('''
SELECT *
FROM myTable
WHERE date >= ''' + date_filter + '''
''')
I try it on that way but I got the following error:
builtins.TypeError: can only concatenate str (not "datetime.datetime") to str
It is possible to apply the filter like that?
Thanks!
Yes, you can do it. To avoid sql injections, the best way is not using the python formatting facilities, but the sql parameters & placeholders (see that you donĀ“t need the single quotes ' as the placeholder does the job and converts the type of the variable):
now = dt.datetime.now()
date_filter = now - timedelta(days=3)
dq_connection = mysql.connector.connect(user='user', password='pass', host='localhost', database='db')
engine = create_engine('localhost/db')
cursor = db_connection.cursor(buffered=True)
query = "SELECT * FROM myTable WHERE date >=%s"
cursor.execute(query,(date_filter,))
Also, you had a mistake in your cursor, it should be db_connection.cursor. The last comma after date_filter is ok because you need to send a tuple.
In case you need more than one paremeter, you can place more than one placeholder:
query = "SELECT * FROM myTable WHERE date >=%s and date<=%s"
cursor.execute(query,(date_filter,other_date))
You can just do something like:
WHERE date >= ''' + str(date_filter) + '''
to represent the date as string as not a datetime object.
You can try with this:
date_f = str(date_filter)
query = ('''
SELECT *
FROM myTable
WHERE date >= "{}"
'''.format(date_f))
I am using pandas.io.sql to execute a SQL script that contains CTE and would like to do something like this:
import pandas.io.sql as psql
param1 = 'park'
param2 = 'zoo'
sqlstr = ("""WITH CTE_A AS (
SELECT *
FROM A
WHERE A.Location = param1),
CTE_B AS (
SELECT *
FROM B
WHERE B.Location = param2)
SELECT A.*, B.*
FROM C
INNER JOIN A
ON C.something = A.something
INNER JOIN B
ON C.something = B.something
WHERE C.combined = param1 || param2
)
I would like to do something like this
result = psql.frame_query(sqlstr, con = db, params = (param1,param2))
Could anyone help me in passing the two parameters using Pandas?
The only way that I know how to do something like this is to do the following. It doesn't however take advantage of the psql package in Pandas.
import pyodbc
import pandas
conn = pyodbc.connect('yourconnectionstring')
curs = conn.cursor()
param1 = 'park'
param2 = 'zoo'
sqlstr = """WITH CTE_A AS (
SELECT *
FROM A
WHERE A.Location = param1),
CTE_B AS (
SELECT *
FROM B
WHERE B.Location = param2)
SELECT A.*, B.*
FROM C
INNER JOIN A
ON C.something = A.something
INNER JOIN B
ON C.something = B.something
WHERE C.combined = ?|| ?;"""
q = curs.execute(sqlstr,[param1,param2]).fetchall()
df = pandas.DataFrame(q)
curs.close()
conn.close()
This passes parameters to avoid SQL injection and ends with a DataFrame object containing your results
When using pandas.io.sql in combination with mysql.connector the syntax is as follows:
import pandas.io.sql as psql
import mysql.connector as mysql
db = mysql.connector(host="localhost",user="user",passwd="password")
hour = 7
result = psql.read_sql("select * from table where
`hour` > %(hour)s and `name` = %(name)s",con=db,params={'hour':hour,'name':'John'})
So just enter %(name)s in the query, replace 'name' with whatever name you want. And add an dictionary for params.
I this option does add '' to the string so if for example you need to use it in a table name then this doesn't work. I use regex to clean the string for this. i.e.
import re
table_name = re.sub(r'[\W]', ' ',table_name)
(use r'[\W_]' if the table name also doesn't have underscores)
can any one tell how to calculate a execution time of a MSSQL stored procedure query using python. I have a query like this
import pyodbc
import timer
DSN ='DRIVER=FreeTDS;SERVER=255.8.12.34;PORT=1433;DATABASE=CustomerFile;UID=Cust;
PWD=Cust;TDS_Version=8.0;'
cnxn =pyodbc.connect(DSN)
cursor = cnxn.cursor()
cursor.execute("select * from db.customer")
d = cursor.fetchall()
print d
i want to know the execution time of the query. I dont know how to do that. Pls help
Expected output:
[(1, aa,vir,123/12, aaa#gmailcom,88898976),(2,bb,yuv,23/4, bbb#gmail.com,2124314)]
Time Taken To execute: 10s
from time import time
# your code here
tic = time()
cursor.execute("select * from db.customer")
toc = time()
print toc - tic
python
import datetime
init_time = datetime.datetime.now()
cursor.execute("select * from db.customer" )
end_time = datetime.datetime.now()
exec_time = end_time - init_time
print ( 'exec_time = {} seconds '.format( exec_time.seconds) )