MySQL,Python:选择WHERE-LIKE查询

2024-06-24 13:19:49 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在创建一个控制台界面来添加、编辑和查看我的视频游戏收藏数据库中的条目。在编辑部分我添加了一个搜索功能,以便找到特定的游戏。在搜索的select查询中,我有要从中提取的表的变量以及类似的条件。你知道吗

对于我使用的select查询:

GameQuery = "SELECT Name, Sub_Name, Platform, Barcode, Edition, Overall_Condition, Region, Requirement, Optional FROM AllGames WHERE Name LIKE %s"

然后执行它:

MediaCursor.execute(GameQuery, SearchCriteria)

但如果我要搜索一个名称中包含撇号的游戏,例如Tom Clancy的,它只会执行…就像%s,因为名称中的撇号会将其截断。然后我试着用:

MediaCursor.execute(GameQuery,(SearchCriteria,))

正好对我的处境有用。但是我也不能用一个变量作为表名,这是我需要的。你知道吗

我试过使用:

GameQuery = "SELECT Name, Sub_Name, Platform, Barcode, Edition, Overall_Condition, Region, Requirement, Optional FROM %s WHERE Name LIKE %s"

执行此命令时:

MediaCursor.execute(GameQuery, TableName,(SearchCriteria,))

但它不会用值替换%s。你知道吗

然后我尝试在代码中使用Python元组来处理这种情况

SearchCriteria = raw_input("Input The Game Name: ")
TableName = raw_input("Input The Platform: ")
qy = TableName, (SearchCriteria,)
GameQuery = "SELECT Name, Sub_Name, Platform, Barcode, Edition, Overall_Condition, Region, Requirement, Optional FROM %s WHERE Name LIKE %s" %qy
MediaCursor.execute(GameQuery)

但这只是在MediaCursor.execute(GameQuery)


Tags: name游戏executerequirementconditionselectbarcoderegion
1条回答
网友
1楼 · 发布于 2024-06-24 13:19:49

我修好了。我将TableName变量放在GameQuery行中,并按如下方式执行:

GameQuery = "SELECT Name, Sub_Name, Platform, Barcode, Edition, Overall_Condition, Region, Requirement, Optional FROM " + TableName + " WHERE Name LIKE %s"

MediaCursor.execute(GameQuery,(SearchCriteria))

不过,谢谢你们的帮助。你知道吗

相关问题 更多 >