I am New in python and I tried to connect MySQL with Python using MySQLdb module.
Here comes Pain for me. I am trying to give input in MySQL Query in python. My code is following:
import MySQLdb
import MySQLdb.cursors
import pandas as pd
import json
#from bson import json_util
cnx = MySQLdb.connect(host = 'localhost',
database = 'cb-dev',
user = 'root',
password = 'root',
compress = 1,
cursorclass=MySQLdb.cursors.DictCursor)
# Python Dictionary
d= {"Date": "2017-09-26","Title": "software","Location1": "USA","Location2": "United States",
"Location3": "United States of America","Competency_user": "App\\Job","Comp1_ID": 482,"Comp2_ID": 483,
"Comp3_ID": 484,"Day_rate_lower": 300,"Day_rate_upper": 500,"hourly_rate_lower": 30,"hourly_rate_upper": 50
}
# Query for Sorting Data from Database and get job ID wich are suitable to talent profile
query3 = """SELECT id FROM jobs WHERE Date(jobs.closing_date) >= %(Date)s
AND title LIKE %(Title)s
AND ( location_name_list LIKE %(Location1)s
OR location_name_list LIKE %(Location2)s
OR location_name_list LIKE %(Location3)s)
AND ( EXISTS (SELECT *
FROM competencies
INNER JOIN competency_maps
ON competencies.id =
competency_maps.competency_id
WHERE jobs.id =
competency_maps.competency_mappable_id
AND competency_maps.competency_mappable_type = %(Competency_user)s
AND competency_id IN ( %(Comp1_ID)s, %(Comp2_ID)s, %(Comp3_ID)s ))
OR ( job_rate BETWEEN %(Day_rate_lower)s AND %(Day_rate_upper)s
AND job_type = "day rate" )
OR ( job_rate BETWEEN %(hourly_rate_lower)s AND %(hourly_rate_upper)s
AND job_type = "contract rate" ))"""
print(query3)
cursor = cnx.cursor()
cursor.execute(query3,d)
print (cursor._last_executed)
sorted_job_Id = cursor.fetchall()
When I Run this code it is not give me any Result but when I tried to input manually each place same input it gives me result below:
({'id': 47467},)
I tried to do googling tried to refer past stackflow questions but I have not got correct answers.
it mostly showing me below error:
ProgrammingError: not enough arguments for format string
I tried to print Query with parameters from below statment:
print (cursor._last_executed)
Problem is its not taking "%" sign when LIKE query comes because whenever I Do manually with "%". it Runs and give me Desire Output.
So Now can anyone please tell me How to give placeholder or Run LIKE SQL query in python?
Thanks in Advance