Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How can i use a string in mysql query in python?

In the code below, i have a string which represent the mac number. I want to use it in my query. Normally it will change dynamically, because of that i want to use it as this way. When i run my code in the below i get the error

File "/usr/local/lib/python2.7/dist-packages/mysql/connector/connection.py", line 395, in _handle_result
raise errors.get_exception(packet)
mysql.connector.errors.ProgrammingError: 1054 (42S22): Unknown column ‘B45D50CFEF6A’ in ‘where clause’

import os
import mysql.connector
from mysql.connector.constants import ClientFlag
import json


execfile("/home/manager/test/mysqlconnector.py")

active_ip = ""
hostname = ""
group_id = 0
active_mac = "b45d50cfef6a"

query = "select epp_active_ip, epp_hostname, epp_group_id from epp_inventory where epp_active_mac = " + active_mac.upper()
cursor = connection.cursor(dictionary=True)
cursor.execute(query)
rows = cursor.fetchall()
 #active_ip = ""
 #hostname = ""
 #group_id = 0
for row in rows:
  active_ip = row["epp_active_ip"]
  hostname = row["epp_hostname"]
  group_id = row["epp_group_id"]
  print(group_id)

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

SQL syntax requires single quotes when selecting columns that are strings.

Replace the query = line with the following:

query = f"select epp_active_ip, epp_hostname, epp_group_id from epp_inventory where epp_active_mac = '{active_mac.upper()}'" 
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading