How to use select now() result in another query in Python? - python

I want to use the select now() query result which is executed in Python in another query but I am unable to do so.
My code :
import MySQLdb
db = MySQLdb.connect(host,username,password,databasename)
cursor = db.cursor()
cursor.execute("SELECT NOW()")
dt = cursor.fetchone()
dt = str(dt) #1
cursor2 = db.cursor()
sql2 = "SELECT pid from PRODUCTS where date between DATE_SUB(" + dt + ", INTERVAL 2 HOUR) and " + dt #... query2
cursor2.execute(sql2)
How can I use the date got in #1 in the #query2. It gives me error.
I even used the DATE_FORMAT function to convert it to the same format in which the NOW() function in SQL gives the output. and then tried using it in the SQL query. But still it gives me syntax error.

You can try using %s on that respective dates
sql2 = "SELECT pid from PRODUCTS where date between DATE_SUB(%s, INTERVAL 2 HOUR) and %s"
cursor2.execute(sql2,(dt,dt))

MySQLdb will automagically transform MySQL datetimes into Python native datetime.datetime objects, and Python native datetime.datetime objects into MySQL-correct datetimes, so you don't have any transformation / formatting or whatever to do by yourself. All it takes is to correctly use the db api:
import MySQLdb
db = MySQLdb.connect(host,username,password,databasename)
cursor = db.cursor()
cursor.execute("SELECT NOW()")
dt = cursor.fetchone()[0] # fetchone returns a tuple
print dt # should print a `datetime.datetime` object
# no need for a second cursor here now you have fetched results
# from your previous query
#cursor2 = db.cursor()
# **ALWAYS** use your db connector's placeholders
sql2 = "SELECT pid from PRODUCTS where date between DATE_SUB(%s, INTERVAL 2 HOUR) and %s"
# this way your db connector will take care of proper transformation / formatting / sanitization / escaping etc
cursor.execute(sql2, (dt, dt))

This link could be useful, try it out!:
https://dev.mysql.com/doc/connector-python/en/connector-python-example-cursor-select.html
Here's what it has:
"The task is to select all employees hired in the year 1999 and print their names and hire dates to the console."
import datetime
import mysql.connector
cnx = mysql.connector.connect(user='scott', database='employees')
cursor = cnx.cursor()
query = ("SELECT first_name, last_name, hire_date FROM employees "
"WHERE hire_date BETWEEN %s AND %s")
hire_start = datetime.date(1999, 1, 1)
hire_end = datetime.date(1999, 12, 31)
cursor.execute(query, (hire_start, hire_end))
for (first_name, last_name, hire_date) in cursor:
print("{}, {} was hired on {:%d %b %Y}".format(
last_name, first_name, hire_date))
cursor.close()
cnx.close()

Related

How to use binding in Django Raw SQL

How can I use a single variable to binding in more than one filter in Django SQL?
What I want:
I defined the variable: date
I want to use the same information in the SQL WHERE Clausures: CUR_DATE, ACHIEVED_DATE
def kpiMonitoring(self):
with connections['db'].cursor()as cursor:
import time
date = time.strftime('%Y%m%d')
cursor.execute("""
SELECT * FROM TABLE1
WHERE CUR_DATE = date
AND ACHIEVED_DATE = date
""",[date])
row = dictfetchall(cursor)
cursor.close()
return row
I can do it by this way, but this solution is not scalable:
def kpiMonitoring(self):
with connections['db'].cursor()as cursor:
import time
date = time.strftime('%Y%m%d')
date2 = date
cursor.execute("""
SELECT * FROM TABLE1
WHERE CUR_DATE = %s
AND ACHIEVED_DATE = %s
""",[date, date2])
row = dictfetchall(cursor)
cursor.close()
return row
Is there another way to do it?
You can perform such query with a named parameter:
cursor.execute(
'''SELECT * FROM TABLE1
WHERE CUR_DATE = %(date)s
AND ACHIEVED_DATE = %(date)s''',
{'date': date }
)
another solution is to simply check if the CUR_DATE is the same as the ACHIEVED_DATE and thus use the parameter only once:
cursor.execute(
'''SELECT * FROM TABLE1
WHERE CUR_DATE = %s
AND ACHIEVED_DATE = CUR_DATE''',
[date]
)
but regardless, using raw queries is not a good idea. It often, as you found out yourself, does not scale very well (making use of LEFT OUTER JOINs is usually shorter with the Django ORM), and usually it is less error prone, and less sensitive for database migrations.

mysql.connector.errors.ProgrammingError: Not all parameters were used in the SQL statement. I am trying to insert the whole list as ones

I am trying to save this list of string in my database table all at ones but it's giving me this error and I don't understand I am new to this so can you guys please help me
data = ['Unknown', 'Saqlain', 'fahad', 'Unknown']
mycursor = mydb.cursor()
Date_raw = datetime.datetime.now()
Date = str(Date_raw.strftime("%d%A%b"))
mycursor.execute(f"CREATE TABLE march ( {Date} VARCHAR(255))")
sqlfor = f"INSERT INTO march ({Date}) VALUES(%s)"
mycursor.execute(sqlfor, data)
mydb.commit()``
It works like this but it stores all the names in a single column which i don't want I want all the names in different columns. also my data is dynamic so the list will be different every time
mycursor = mydb.cursor()
Date_raw = datetime.datetime.now()
Date = str(Date_raw.strftime("%d%A%b"))
mycursor.execute(f"CREATE TABLE march ( {Date} VARCHAR(255))")
sqlfor = f"INSERT INTO march ({Date}) VALUE(%s %s %s %s)"
mycursor.execute(sqlfor, data)
mydb.commit()
Simply use executemany which passes a sequence of params into execute call:
mycursor.executemany(sqlfor, [(d,) for d in data])
declare #i INT(11);
SET #i=1;
data = ['Unknown', 'Saqlain', 'fahad', 'Unknown']
mycursor = mydb.cursor()
Date_raw = datetime.datetime.now()
Date = str(Date_raw.strftime("%d%A%b"))
mycursor.execute(f"CREATE TABLE march ( {Date} VARCHAR(255))")
sqlfor = f"INSERT INTO march ({Date}) VALUES(%s)"
WHILE((SELECT ELT(#i,data)) IS NOT NULL)
DO
BEGIN
mycursor.execute(sqlfor, (SELECT ELT(#i,data));
SET #i:= #i+ 1;
mydb.commit();
END;
END WHILE;`
SELECT ELT(1,['100','101']) returns '100' .ELT () returns null when the index is out of bounds

Not all parameters were used in the SQL statement when using python and mysql

hi I am doing the python mysql at this project, I initial the database and try to create the table record, but it seems cannot load data to the table, can anyone here can help me out with this
import mysql.connector
mydb = mysql.connector.connect( host="localhost",user="root",password="asd619248636",database="mydatabase")
mycursor = mydb.cursor()
mycursor.excute=("CREATE TABLE record (temperature FLOAT(20) , humidity FLOAT(20))")
sql = "INSERT INTO record (temperature,humidity) VALUES (%d, %d)"
val = (2.3,4.5)
mycursor.execute(sql,val)
mydb.commit()
print(mycursor.rowcount, "record inserted.")
and the error shows "Not all parameters were used in the SQL statement")
mysql.connector.errors.ProgrammingError: Not all parameters were used in the SQL statement
Changing the following should fix your problem:
sql = "INSERT INTO record (temperature,humidity) VALUES (%s, %s)"
val = ("2.3","4.5") # You can also use (2.3, 4.5)
mycursor.execute(sql,val)
The database API takes strings as arguments, and later converts them to the appropriate datatype. Your code is throwing an error because it isn't expecting %d or %f (int or float) datatypes.
For more info on this you can look here
simply change insert method to
sql = "INSERT INTO record (temperature,humidity) VALUES (%s, %s)"
then it works fine
This works for me.
# Insert from dataframe to table in SQL Server
import time
import pandas as pd
import pyodbc
# create timer
start_time = time.time()
from sqlalchemy import create_engine
df = pd.read_csv("C:\\your_path_here\\CSV1.csv")
conn_str = (
r'DRIVER={SQL Server Native Client 11.0};'
r'SERVER=Excel-Your_Server_Name;'
r'DATABASE=NORTHWND;'
r'Trusted_Connection=yes;'
)
cnxn = pyodbc.connect(conn_str)
cursor = cnxn.cursor()
for index,row in df.iterrows():
cursor.execute('INSERT INTO dbo.Table_1([Name],[Address],[Age],[Work]) values (?,?,?,?)',
row['Name'],
row['Address'],
row['Age'],
row['Work'])
cnxn.commit()
cursor.close()
cnxn.close()

SQL insert into MS Server DB using Python not working

I am trying to insert data into a table that has already been created. The code does not throw any error but simply does not writes into the DB.
I think there is problem with the timestamp, may be.
If any of you could please have a look at the code and provide some pointers, that would be great.
TIA!!
Cheers
import pyodbc
import datetime
import time
def connect_db():
db = pyodbc.connect("Driver={SQL Server Native Client 11.0};"
"Server=xxxxx\SQLEXPRESS;"
"Database=test;"
"Trusted_Connection=yes;"
"uid=xxx;"
"password=xyz")
cursor = db.cursor()
ts = time.time()
timestamp = datetime.datetime.fromtimestamp(ts).strftime('%Y-%m-%d %H:%M:%S')
sql = "INSERT into dbo.test_tbl VALUES (3,'ITS','Paris', 10, 'Laptop', %)" % (timestamp)
cursor.execute(sql)
db.commit()
cursor.close()
db.close()
"INSERT into dbo.test_tbl VALUES (3,'ITS','Paris', 10, 'Laptop', %)" % (timestamp)
I think you have to add s after %
"INSERT into dbo.test_tbl VALUES (3,'ITS','Paris', 10, 'Laptop', '%s')" % (timestamp)

Replace L, in SQL results in python

I'm running pyodbc connected to my db and when i run a simply query I get a load of results back such as
(7L, )(12L,) etc.
How do I replace the the 'L, ' with '' so I can pass the ids into another query
Thanks
Here's my code
import pyodbc
cnxn = pyodbc.connect('DSN=...;UID=...;PWD=...', ansi=True)
cursor = cnxn.cursor()
rows = cursor.execute("select id from orders")
for row in rows:
test = cursor.execute("select name from customer where order_id = %(id)s" %{'id':row})
print test
Use parameters:
...
test = cursor.execute("select name from customer where order_id = ?", row.id)
...
The L after the number indicates that the value is a long type.

Categories

Resources