感谢您的阅读。我对SQL有一些经验,对python非常陌生。
在下面的代码中,我正在访问python2.7中的2个数据库--连接可以工作。我可以在一条语句中查询具有串行#s的表,没有问题。然后,我希望查询一个名称与另一个数据库中的序列号相匹配的表,并提取"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)
*打印输出(Active_devices)(u‘ccnbsc000001’,),(u'ccnbsc00000002',)
打印输出(当前设备) ccnbsc00000001 (这是正确的输出/值)
但是我在SQL查询中得到了这个错误,这意味着它保留了周围的字符‘和')
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**发布于 2018-11-01 05:10:01
Python MySQL库通常在将字符串参数作为参数传递给它们时插入引号,因为通常您确实需要这些引号。这就是你看到引号的原因。
这里的修正很简单:与将这些值作为参数传递给游标不同,您可以像其他Python字符串那样直接将这些值插入字符串中。就像这样:
hb_cursor.execute('SELECT MAX(stamp) FROM {0}'.format(currentdevice))Python参数将删除字符串周围的引号,MySQL游标参数将保留引号。
https://stackoverflow.com/questions/53095328
复制相似问题