my_connect = mysql.connector.connect(
host="localhost",
user="xyz",
passwd="xyz",
database="tracking"
)
my_conn = my_connect.cursor()
x = input("enter name")
query="SELECT * FROM trackingtable WHERE Customer_Name = \"x\"";
print(query)
my_conn.execute(query)
my_conn.close()
Query printed statement
How do i get the proper query using the input from user? I tried using placeholders but I couldn't get them to work
Try:
query = f"SELECT * FROM trackingtable WHERE Customer_Name = {x}"
It's an f-string in which you can plug in variables via {}.
If you need the "s inside the query:
query = f'SELECT * FROM trackingtable WHERE Customer_Name = "{x}"'
Do you need the ; at the end?
Related
i have a question regarding variable injection into sql query with sqlalchemy/python(3.8).
What i researched so far was adding %s and also email_address=? and then adding it (email_address) but without success
What i am trying to do is capture user input and run a select query dynamically.
print(" What is the email address??")
email_address = input()
conn = create_engine("mssql+pyodbc://test_table:username#127.0.0.1:3306/test_db?driver=SQL Server?Trusted_Connection=yes'", echo = False)
sql = pd.read_sql('Select id,email_address from test_table where email_address = email_address', conn)
print(sql)
try:
print(" What is the email address??")
email_address = input()
conn = create_engine("mssql+pyodbc://test_table:username#127.0.0.1:3306/test_db?driver=SQL Server?Trusted_Connection=yes'", echo = False)
sql = pd.read_sql('Select id,email_address from test_table where email_addres=?', conn, params=(email_addres,))
print(sql)
I was using sqlite however moved to MySqL
Sqlite code that worked:
#app.route('/api/v1/users/user', methods=['GET'])
def api_filter():
query_parameters = request.args
userid = query_parameters.get('userid')
username = query_parameters.get('username')
query = "SELECT * FROM tblUser WHERE"
to_filter = []
if userid:
query += ' user_id=? AND'
to_filter.append(userid)
if username:
query += ' username=? AND'
to_filter.append(username)
if not (userid or username):
return page_not_found(404)
query = query[:-4] + ';'
conn = sqlite3.connect('dbApp.db')
conn.row_factory = dict_factory
cur = conn.cursor()
results = cur.execute(query, to_filter).fetchall()
return jsonify(results)
Now when I change it to MySQL it does not work:
#app.route('/api/v1/users/user', methods=['GET'])
def api_filter():
query_parameters = request.args
userid = query_parameters.get('userid')
username = query_parameters.get('username')
query = "SELECT * FROM tblUser WHERE"
to_filter = []
if userid:
query += ' user_id=? AND'
to_filter.append(userid)
if username:
query += ' username=? AND'
to_filter.append(username)
if not (userid or username):
return page_not_found(404)
query = query[:-4] + ';'
conn = mysql.connector.connect(host="localhost", user="root", password="green", database="dbApp")
conn.row_factory = dict_factory
cur = conn.cursor()
results = cur.execute(query, to_filter).fetchall()
return jsonify(results)
The error returned:
results = cur.execute(query, to_filter).fetchall()
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/mysql/connector/cursor_cext.py", line 260, in execute
raise errors.ProgrammingError(
mysql.connector.errors.ProgrammingError: Not all parameters were used in the SQL statement
127.0.0.1 - - [28/Dec/2020 17:47:11] "
This is after running:
http://127.0.0.1:5000/api/v1/users/user?userid=3&username=Jo
http://127.0.0.1:5000/api/v1/users/user?userid=3
http://127.0.0.1:5000/api/v1/users/user?username=Jo
Also added this:
from flask import request, jsonify
import mysql.connector
Here is what the documentation says:
cursor.execute(operation, params=None, multi=False)
This method executes the given database operation (query or command).
The parameters found in the tuple or dictionary params are bound to
the variables in the operation. Specify variables using %s or %(name)s
parameter style (that is, using format or pyformat style). execute()
returns an iterator if multi is True.
I think there are two problems with your code: you are using ? for bind variables instead of %s, and you are passing in a list instead of a tuple. Alternatively use named parameters and pass in the values with a dict. Try both and see what you like most.
user_id = %s" and to_filter = (userid, ). You can use the list you have now and just convert it with tuple().
" user_id = %{user_id}" and set to_filter = {'user_id': userid }.
It is cleaner to build a list of conditions, then ' AND '.join(conditions) instead of removing the extra AND. You can simplify the code a little bit by just leaving out the ';'.
I am trying to use one query output into other. but not getting the correct result. Can you please help me how to do this?
Example:
query1 = "select distinct lower(tablename) as tablename from medaff.imedical_metadata where object_type = 'View'"
output of above query is :
tablename
vw_mdcl_insght
vw_fbms_interactions
I want to use above output in other query. Something like this-
query2 = "select * from medaff.imedical_business_metadata where objectname in ('vw_mdcl_insght', 'vw_fbms_interactions')"
How to do this part in python?
I am using below code to run the query:
conn = redshift_conn()
with conn.cursor() as cur:
query1 = "select distinct lower(tablename) as tablename from medaff.imedical_metadata where object_type = 'View'"
cur.execute(sql_query)
result = cur.fetchall()
print(result)
conn.commit()
query2 = "select * from medaff.imedical_business_metadata where objectname in ('vw_mdcl_insght', 'vw_fbms_interactions')"
cur.execute(sql_query)
result = cur.fetchall()
print(result)
conn.commit()
I think you can just use an in query:
select ibm.*
from medaff.imedical_business_metadata ibm
where ibm.objectname in (select lower(im.tablename) as tablename
from medaff.imedical_metadata im
where im.object_type = 'View'
);
It is better to let the database do the work.
I used the below code:
query = "select distinct lower(tablename) from medaff.imedical_metadata where object_type = 'View'"
cur.execute(query)
res = cur.fetchall()
print(res)
res = tuple([item[0] for item in res])
res = str(res)
Code looks like this:
import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="yourusername",
passwd="yourpassword",
database="mydatabase"
)
mycursor = mydb.cursor()
sql = """SELECT * FROM customers WHERE address LIKE '%way%'"""
mycursor.execute(sql)
myresult = mycursor.fetchall()
for x in myresult:
print(x)
This will select all the records whose address contain care like "way".
How to insert the wildcard dynamically by using %s
Basically I want to know how to use %s instead of 'way' in python so that the code will be more flexible.
try like below
query ="SELECT * FROM customers WHERE\
address LIKE '%"+variable+"%'"
Try escaping the percentage by doubling them.
>>> res = """SELECT * FROM customers WHERE address LIKE '%%%s%%'""" % ('way')
>>> res
"SELECT * FROM customers WHERE address LIKE '%way%'"
I'm using a mysql lib on python, and when I try to do this query:
SELECT product FROM database1.contacts WHERE contact="%s" % (contact)
I get this:
(u'example',)
But I expect this:
example
Here is my code:
import mysql.connector
db_user = "root"
db_passwd = ""
db_host = "localhost"
db_name = "database1"
connector = mysql.connector.connect(user=db_user, password=db_passwd, host=db_host, database=db_name,
buffered=True)
cursor = connector.cursor()
contact = "943832628"
get_product_sql = 'SELECT product FROM database1.contacts WHERE contact="%s"' % (contact)
cursor.execute(get_product_sql)
for product in cursor:
print product
You are printing the whole row; print just the first column:
for product in cursor:
print product[0]
or use tuple unpacking in the loop:
for product, in cursor:
print product