从python搜索mysql查询
我将我的Python程序与MYSQL数据库链接,在该数据库中,我有一个名为“user_data”的表,其中存储了不同的用户数据。我试图从数据库中选择一个特定的数据,并显示它或将其用于其他目的。下面的代码很有魅力:从python搜索mysql查询,python,mysql,Python,Mysql,我将我的Python程序与MYSQL数据库链接,在该数据库中,我有一个名为“user_data”的表,其中存储了不同的用户数据。我试图从数据库中选择一个特定的数据,并显示它或将其用于其他目的。下面的代码很有魅力: self.cursor = self.db.cursor() self.cursor.execute("SELECT * from user_data WHERE Name = 'Anup'") rows = self.cursor.fetchone()
self.cursor = self.db.cursor()
self.cursor.execute("SELECT * from user_data WHERE Name = 'Anup'")
rows = self.cursor.fetchone()
print(rows)
然而,这个程序实际上不适合在数据库中搜索。因此,当我试图将我的程序修改为可行的程序时,没有可用的输出。或者干脆将输出显示为无。以下是显示错误的代码:
self.cursor = self.db.cursor()
name="Anup"
self.cursor.execute("SELECT * from user_data WHERE Name = '%s'",('name'))
rows = self.cursor.fetchone()
print(rows)
我认为你的代码有问题 试试这个
self.cursor = self.db.cursor()
name="Anup"
self.cursor.execute("SELECT * from user_data WHERE Name = '%s'" % (name))
rows = self.cursor.fetchone()
print(rows)
您需要使用元组(注意名称
后的逗号):
您应该使用如下参数化查询:
name="Anup"
self.cursor.execute("SELECT * from user_data WHERE Name = %s", (name,))
这里请注意,您没有向查询中添加单引号(DBAPI驱动程序将为您添加单引号),元组(或其他序列,如列表)作为参数传递给cursor.execute()
另一种方法是将命名参数与作为字典传递的值一起使用:
name="Anup"
self.cursor.execute("SELECT * from user_data WHERE Name = %(name)s", {'name': name})
虽然这会起作用,但使用字符串插值生成查询并不是一个好主意。改为使用参数化查询可以避免常见的SQL注入漏洞。@user5177957:根据我的评论,您不应该这样做,因为可能会发生SQL注入。关于这一点,有一些信息(这是针对SQLite的,但对于其他驱动程序(如MySQL)也是一样)为了避免SQL注入,您可以使用这一行
self.cursor.execute(“SELECT*from user_data WHERE Name=%s”,('Name'))
@SaurabhPandey:是的,除了传递文本字符串'Name'
。应使用变量name
,即(name,)
,而不是字符串'name'
。
name="Anup"
self.cursor.execute("SELECT * from user_data WHERE Name = %(name)s", {'name': name})