简体   繁体   中英

python 2.7 variable substitution issue in MYsql statement

Thank you for reading. I have some experience with SQL, very new to python.

In the below code, i am accessing 2 databases in python 2.7 The connections work. I can query a tables that has a serial #s for devices in one statement with no issue. I then want to query a table which name matches that serial number in another database, pulling the latest value of the "Stamp" field. All of this works when i explictly name the table ccnbsc00000001, but when using variable subsitution, it fails.

When the variable currentdevice is substituted, extras characters are included. When i print that variable, those character are not present in that output. here is the code, and the error result at the bottom

#!/usr/bin/python
### Imports
import datetime
import mysql.connector
#Connect to heartbeat results database
hb_db = mysql.connector.connect(
  host="localhost",
  user="otheruser",
  passwd="******",
  database="active_devices"
)
#Connect to heartbeat results database
device_Settings_db = mysql.connector.connect(
  host="localhost",
  user="otheruser",
  passwd="******",
  database="active_devices"
)
device_settings_cursor = device_settings_db.cursor()
hb_cursor = hb_db.cursor()
## Get deviuce serial#
device_settings_cursor.execute('select device_serial from devices')
active_devices = device_settings_cursor.fetchall()
print ("these are the current devices:")
print (active_devices)
for device in active_devices:

 currentdevice = device[0]
 print(currentdevice)

 print ("SELECT MAX(stamp) FROM (%s)" , (currentdevice,) )
 hb_cursor.execute('SELECT MAX(stamp) FROM (%s)' , (currentdevice,) )

 laststamp = hb_cursor.fetchone
 laststamp = laststamp[0]
 print("Last time stamp is:")
 print(laststamp)


*

Output of print(active_devices) [(u'ccnbsc00000001',), (u'ccnbsc00000002',)]

output of print(currentdevice) ccnbsc00000001 (This is the correct output/value)

but I get this error in the SQL query that implies it has kept the surrounding characters ' and ')

Traceback (most recent call last):
  File "./hb_notify.py", line 61, in <module>
    hb_cursor.execute('SELECT MAX(stamp) FROM (%s)' , (currentccn,) )
  File "/usr/lib/python2.7/site-packages/mysql/connector/cursor.py", line 551, in execute
self._handle_result(self._connection.cmd_query(stmt))
  File "/usr/lib/python2.7/site-packages/mysql/connector/connection.py", line 490, in cmd_query
  result = self._handle_result(self._send_cmd(ServerCmd.QUERY, query))
File "/usr/lib/python2.7/site-packages/mysql/connector/connection.py", line 395, in _handle_result
  raise errors.get_exception(packet)
mysql.connector.errors.ProgrammingError: 1064 (42000): You have an error in your **SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near ''ccnbsc00000001')' at line 1**

Python MySQL libraries commonly insert quotation marks when you pass string arguments to them as arguments, because usually you do actually want those quotation marks. This is why you're seeing quotation marks.

The fix here is easy: instead of passing those values as arguments to your cursor, you can just insert those values directly into the string like you would if it were any other Python string. Like so:

hb_cursor.execute('SELECT MAX(stamp) FROM {0}'.format(currentdevice))

Python string arguments will remove quotes around a string, MySQL cursor arguments will keep the quotes.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM