mysql语句中的python2.7变量替换问题

ulmd4ohb  于 2021-06-18  发布在  Mysql
关注(0)|答案(1)|浏览(316)

谢谢你的阅读。我对sql有一些经验,对python非常陌生。
在下面的代码中,我正在访问Python2.7中的两个数据库,连接工作正常。我可以在一个语句中查询具有设备序列号的表,没有问题。然后我想在另一个数据库中查询一个名称与序列号匹配的表,提取“stamp”字段的最新值。当我明确地将表命名为ccnbsc00000001时,所有这些都可以工作,但是当使用变量替代时,它失败了。
当替换可变电流装置时,包括额外字符。当我打印这个变量时,这些字符不会出现在输出中。下面是代码,错误结果在底部


# !/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)

* 

打印输出(有源设备)[(u'ccnbsc00000001',),(u'ccnbsc00000002',)]
打印输出(currentdevice)ccnbsc00000001(这是正确的输出/值)
但是我在sql查询中得到了这个错误,这意味着它保留了周围的字符'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**
kyks70gy

kyks70gy1#

pythonmysql库通常在将字符串参数作为参数传递给它们时插入引号,因为通常您确实需要这些引号。这就是为什么你会看到引号。
这里的修复很简单:不需要将这些值作为参数传递给游标,只需将这些值直接插入到字符串中,就像插入任何其他python字符串一样。像这样:

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

python字符串参数将删除字符串周围的引号,mysql游标参数将保留引号。

相关问题